我有两个字符,a和b.我试图15 bit 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);
Run Code Online (Sandbox Code Playgroud)
有人可以帮我理解这是如何工作的,所以我可以学会在任何位置留下任何位或空位?
我假设是"第八位",你的意思是最重要的一点......试试:
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);
Run Code Online (Sandbox Code Playgroud)
这是关键...如果你想制作一个m位长的位掩码,从右边开始n位,你可以使用这个表达式:
mask = ((1 << m) - 1) << n;
Run Code Online (Sandbox Code Playgroud)
然后,您可以使用&运算符将不在掩码中的每个位设置为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);
Run Code Online (Sandbox Code Playgroud)