I was curious why the following only works when defining an unsigned
char:
#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. 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?
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
.
Slightly off topic, but the simplest fix for your code is just to switch the exit condition to d != 0 && ix < 8
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.