【发布时间】:2017-07-10 21:14:22
【问题描述】:
我知道如何进行位移,但我的值似乎超出了边缘,并且我失去了原始值以作为尝试保留 8 位的回报。
【问题讨论】:
-
这很可能是一个有趣的问题,但您必须提供更多信息 - 例如,示例代码、示例输入和显示问题的示例输出。 minimal reproducible example
标签: arrays integer bit-manipulation unsigned bits
我知道如何进行位移,但我的值似乎超出了边缘,并且我失去了原始值以作为尝试保留 8 位的回报。
【问题讨论】:
标签: arrays integer bit-manipulation unsigned bits
对于无符号 16 位整数:
unsigned short val16 = 0x1234;
unsigned char enc[2];
enc[0] = val16 & 0xff; // stores 0x34 to enc[0]
enc[1] = val16 >> 8 & 0xff; // stores 0x12 to enc[1]
对于无符号 32 位整数:
unsigned int val32 = 0x12345678;
unsigned char enc[4];
enc[0] = val32 & 0xff; // stores 0x78 to enc[0]
enc[1] = val32 >> 8 & 0xff; // stores 0x56 to enc[1]
enc[2] = val32 >> 16 & 0xff; // stores 0x34 to enc[2]
enc[3] = val32 >> 24 & 0xff; // stores 0x12 to enc[3]
更新
与十进制文字完全相同的代码是:
unsigned short val16 = 4660; // 4660 = 0x1234
unsigned char enc[2];
enc[0] = val16 & 255;
enc[1] = val16 >> 8 & 255;
和
unsigned int val32 = 305419896; // 305419896 = 0x12345678
unsigned char enc[4];
enc[0] = val32 & 255;
enc[1] = val32 >> 8 & 255;
enc[2] = val32 >> 16 & 255;
enc[3] = val32 >> 24 & 255;
【讨论】: