I wrote the following code to understand the bit-wise right shift operation,
unsigned long a = 0;
unsigned long b = 0xFFFFFFFF;
a = ~a; // now a is equal to b
a = a >> 1;
b = b >> 1;
printf("a = %x\n", a); // result: a = 0xFFFFFFFF
printf("b = %x\n", b); // result: b = 0x7FFFFFFF
I though that before the right shift operation a and b were both equal to 0xFFFFFFFF
, and then after the right shift the results ought to be identical. But the results showed that
a = 0xFFFFFFFF
b = 0x7FFFFFFF
It seemed the MSB of a got 1, while the MSB of b got 0. Why did this difference happen?