c++ - 高级位操作,在任何位置留下空位

标签 c++

我有两个字符,ab。我试图在这些字符中存储一个 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/

相关文章:

c++ - 为什么在头文件中定义类有效但函数无效

c++ - boos::asio async_wait 似乎在阻塞

c++ - 将 numpy 数组与 boost.python : pyublas or boost. numpy 交换?

c++ - 方法返回类型的前向声明

c++ - 更改 DEF 文件中的函数签名

c++ - Visual Studio 编译的 Qt 插件在 Release模式下无法加载

c++ - 在 MS Visual Studio 2017 中将 boost::thread 与 CMake 一起使用会导致两个编译器错误

c++ - 我无法运行将 allegro5 与 cmake 结合使用的程序

c++ - 在 TCLAP 中显示自定义帮助消息

c++ - boost::shared_ptr::shared_ptr(const boost::shared_ptr&)' 被隐式声明为已删除