简体   繁体   English

在C,C ++中由位移运算符(<<,>>)进行位移的位

[英]Bits shifted by bit shifting operators(<<, >>) in C, C++

can we access the bits shifted by bit shifting operators(<<, >>) in C, C++? 我们如何访问C,C ++中由移位运算符(<<,>>)移位的位? For example: 23>>1 can we access the last bit shifted(1 in this case)? 例如:23 >> 1我们可以访问最后移位的位(在这种情况下为1)吗?

No, the shift operators only give the value after shifting. 不,移位运算符仅在移位后才给出值。 You'll need to do other bitwise operations to extract the bits that are shifted out of the value; 您将需要执行其他按位运算,以提取移出该值的位。 for example: 例如:

unsigned all_lost  = value & ((1 << shift)-1);  // all bits to be removed by shift
unsigned last_lost = (value >> (shift-1)) & 1;  // last bit to be removed by shift
unsigned remaining = value >> shift;            // lose those bits

By using 23>>1 , the bit 0x01 is purged - you have no way of retrieving it after the bit shift. 通过使用23>>1 ,位0x01被清除-移位后您将无法取回它。

That said, nothing's stopping you from checking for the bit before shifting: 也就是说,没有什么可以阻止您移位之前检查一下位:

int  value   = 23;
bool bit1    = value & 0x01;
int  shifted = value >> 1;

You can access the bits before shifting, eg 您可以移位之前访问这些位,例如

value  = 23;          // start with some value
lsbits = value & 1;   // extract the LSB
value >>= 1;          // shift

It worth signal that on MSVC compiler an intrinsic function exists: _bittest 值得说明的是,在MSVC编译器上存在一个内部函数: _bittest

that speeds up the operation. 这样可以加快操作速度。

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

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