简体   繁体   English

C ++:如何将uint32中的相关位放入uint8中?

[英]c++: how to put relevant bits from uint32 into uint8?

I have a uint32 that I've flagged some bits on: 我有一个uint32,上面已经标记了一些位:

uint32 i = 0;
i |= (1 << 0);
i |= (1 << 5); 
i |= (1 << 13);
i |= (1 << 19);
...

I want to convert it to a uint8 (by getting the state of its first 8 bits and disregarding the rest). 我想将其转换为uint8(通过获取其前8位的状态而忽略其余部分)。 Obviously I could do this: 显然我可以这样做:

uint8 j = 0;
for (int q = 0; q < 8; q++)
{
    if (i & (1 << q))
    {
        j |= (1 << q);
    }
}

But is there a fancy bitwise operation I can use to transfer the bits over in one fell swoop, without a loop? 但是,是否有一种花哨的按位操作,我可以使用一次转移就将这些位转移过来而没有循环?

Why not just mask those last 8 bits instead of running a loop over to see if individual bits are set? 为什么不仅仅屏蔽最后8位而不是循环查看是否设置了单个位?

const unsigned char bitMask = 0xFF;
j = (i & bitMask);

Note that C++ 14 though allows you to define binary literals right away 请注意,尽管C ++ 14允许您立即定义二进制文字

const unsigned char bitMask = 0b1111'1111;

The above is all you need. 以上就是您所需要的。 Just in case, if you need to get the subsequent byte positions, use the same mask 0xFF and make sure to right shift back the result to get the desired byte value. 以防万一,如果需要获取后续的字节位置,请使用相同的掩码0xFF ,并确保将结果右移以获取所需的字节值。

You can achieve the same result by simply assigning the uint32 value to uint8. 您只需将uint32值分配给uint8即可达到相同的结果。

int main()
{
  unsigned int i = 0x00000888;
  unsigned char j = i;
  cout<<hex<<i<<endl;
  cout<<hex<<+j<<endl;
  return 0;
}

output: 888 88 输出:888 88

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM