samuelbrody1249
samuelbrody1249

Reputation: 4767

Bitwise operators on signed ints

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?

Upvotes: 1

Views: 37

Answers (1)

Tommy
Tommy

Reputation: 100652

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, i.e. the sign bit is filled with a copy of the bit that left it upon every shift.

This is often a better choice because e.g. 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.

Upvotes: 1

Related Questions