繁体   English   中英

是否正确连接按位运算?

[英]Correct way to concatenate bitwise operations?

我需要连接一些按位操作,但当前输出似乎是错误的。 拆分操作类似于:

unsigned char a = 0x12
unsigned char x = 0x00;
x = a << 4;
x = x >> 4;

预期结果x = 0x02; 当前结果x = 0x02;

如果我尝试连接操作,结果不正确:

unsigned char a = 0x12
unsigned char x = 0x00;
x = (a << 4) >> 4;

预期结果x = 0x02; 当前结果x = 0x12;

提前感谢任何建议。

   unsigned char a = 0x12;
   unsigned char x = 0x00;
   x = static_cast<unsigned char>(a << 4) >> 4;   

问题是(a << 4)被强制转换为int,因此(0x12 << 4) >> 4基本上是0x12

请参阅https://en.cppreference.com/w/cpp/language/implicit_conversion#Integral_promotion

编译器不对>>和<<操作应用整体促销

你可能会这么认为

x = (a << 4) >> 4;

将使用字节宽的寄存器进行操作,但编译器在执行移位之前将char a提升为int,保留向左移位的位。

你可以这样解决这个问题:

x = ((a << 4) & 0xff) >> 4;

同样,问题在于整体促销会保留比特直到最终演员表。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM