在C ++中将每5位转换为整数值

时间:2017-10-31 19:52:05

标签: c++

首先,如果有人对我有更好的头衔,请告诉我。

以下是我尝试使用C ++进行自动化的过程示例

我有一个以这种格式显示的值数组: 9C07 9385 9BC7 00 9BC3 9BC7 9385

我需要将它们转换为二进制,然后将每5位转换为十进制,如下所示,最后一位是标志:

我这里只用第一个字来做这件事。

9C07

10011 | 10000 | 00011 | 1

19 | 16 | 3

这些实际上是x,y,z坐标,最后一位决定了它们在' 0'中的顺序。会使x = 19 y = 16 z = 3和' 1'是x = 16 y = 3 z = 19

我已经有一个填充了这些十六进制值的缓冲区,但我不知道从哪里开始。

2 个答案:

答案 0 :(得分:0)

以下代码将从value的16个最低有效位(即其最低有效字)中提取三个坐标和标志。

int flag = value & 1; // keep only the least significant bit
value >>= 1; // shift right by one bit
int third_integer = value & 0x1f; // keep only the five least significant bits
value >>= 5; // shift right by five bits
int second_integer = value & 0x1f; // keep only the five least significant bits
value >>= 5; // shift right by five bits
int first_integer = value & 0x1f; // keep only the five least significant bits
value >>= 5; // shift right by five bits (only useful if there are other words in "value")

你需要的是一些循环在数组的每个单词上执行此操作。

答案 1 :(得分:0)

我认为这些是整数文字,而不是字符串?

执行此操作的方法是按位右移(>>)和按位AND(&)

#include <cstdint>

struct Coordinate {
        std::uint8_t x;
        std::uint8_t y;
        std::uint8_t z;
        constexpr Coordinate(std::uint16_t n) noexcept
        {
                if (n & 1) { // flag
                        x = (n >> 6) & 0x1F; // 1 1111
                        y = (n >> 1) & 0x1F;
                        z = n >> 11;
                } else {
                        x = n >> 11;
                        y = (n >> 6) & 0x1F;
                        z = (n >> 1) & 0x1F;
                }
        }
};