我知道如何进行位移,但是我的值似乎偏离了边缘,并且在尝试保留8位时我失去了原始值。
答案 0 :(得分:1)
对于无符号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;