我有两个字符,a
和 b
。我试图在这些字符中存储一个 15 位 int
,但我必须让第一个字符的第 8 位保持不变。
我知道如何在第 8 个字符没有间隙的情况下执行此操作:
unsigned int num = 32767;
unsigned char a = num;
unsigned char b = (num & 0xFF00) >> 8;
cout << "The num is: " << (unsigned int)a + ((unsigned int)b << 8);
谁能帮我理解这是如何工作的,这样我就可以学会在任何位置留出任何一个或多个空位?
最佳答案
我假设“第八位”是指最高有效位...尝试:
unsigned int num = 32767;
unsigned char a = 0, b = 0;
a &= 0x80; // Preserve only the MSB of a
a |= (num & ((1 << 7) - 1)); // Bit-wise OR the seven LSBs of num
b = (num & (((1 << 8) - 1) << 7)) >> 7; // Set b equal to the remaining eight bits of num.
cout << "The num is: " << (unsigned int)(a & 0x7F) + ((unsigned int)b << 7);
这里是关键...如果你想制作一个从右边开始 n 位的 m 位长的位掩码,你可以使用这个表达式:
mask = ((1 << m) - 1) << n;
然后,您可以只使用 & 运算符将不在掩码中的每个位设置为 0,>> 移动结果,并使用 = 或 |= 适本地设置位。
备选
如果您指的是最低有效位而不是最高有效位,这里有一个替代解决方案:
unsigned int num = 32767;
unsigned char a = 0, b = 0;
a &= 0x01; // Preserve only the MSB of a
a |= (num & ((1 << 7) - 1)) << 1; // Bit-wise OR the seven LSBs of num
b = (num & (((1 << 8) - 1) << 7)) >> 7; // Set b equal to the remaining eight bits of num.
cout << "The num is: " << (unsigned int)((a & 0xFE) + ((unsigned int)b << 7);
关于c++ - 高级位操作,在任何位置留下空位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21209336/