简体   繁体   English

有符号整数上的位运算符

[英]Bitwise operators on signed ints

I was curious why the following only works when defining an unsigned char:我很好奇为什么以下仅在定义unsigned字符时才有效:

#define BITS 8

unsigned char d = 0b00001011; // will fail if doing `char d`
d = ~d;
char buffer[BITS+1] = "00000000";
for(int ix=0; d!=0; d>>=1, ix++) {
    buffer[BITS-1-ix] = d&1 ? '1' : '0';
}
printf("%s\n", buffer);

Otherwise I get a SegFault, which I'm guessing is due to the d>>=1 on the signed type.否则我会得到一个 SegFault,我猜这是由于签名类型上的d>>=1造成的。 Why does that occur exactly though?为什么会发生这种情况呢? Wouldn't it have the same bit pattern and doing >>1 would just push the bits to the right once?它不会具有相同的位模式并且执行>>1只会将位向右推一次吗?

Shifting a negative signed number rightward has implementation-defined behaviour;将负符号数右移具有实现定义的行为; exactly what it does will depend on your compiler.它的确切作用取决于您的编译器。

Likely your compiler is using two's complement and arithmetic shifts right, ie the sign bit is filled with a copy of the bit that left it upon every shift.您的编译器可能正在使用二进制补码和算术右移,即符号位填充有每次移位时留下的位的副本。

This is often a better choice because eg it means that -4 >> 1 is -2 rather than, in an 8-bit quantity, being 126 .这通常是一个更好的选择,因为例如它意味着-4 >> 1-2而不是 8 位数量的126

Slightly off topic, but the simplest fix for your code is just to switch the exit condition to d != 0 && ix < 8 .稍微偏离主题,但对您的代码最简单的解决方法是将退出条件切换为d != 0 && ix < 8

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

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