Back to right shift: arithmetic -vs- logical
// show_bytes() defined on pg. 45, Bryant and O'Halloran
int main() {
int a = 1048576;
int a_rs8 = a >> 8;
int b = -1048576;
int b_rs8 = b >> 8;
printf("a = %d:\t", a);
show_bytes((byte_pointer) &a, sizeof(int));
printf("a >> 8 = %d:\t", a_rs8);
show_bytes((byte_pointer) &a_rs8, sizeof(int));
printf("b = %d:\t", b);
show_bytes((byte_pointer) &b, sizeof(int));
printf("b >> 8 = %d:\t", b_rs8);
show_bytes((byte_pointer) &b_rs8, sizeof(int));
return 0;
}
$ ./right_shift
a = 1048576: 00 00 10 00
a >> 8 = 4096: 00 10 00 00
b = -1048576: 00 00 f0 ff
b >> 8 = -4096: 00 f0 ff ff
(run on a little-endian machine)
The right-shift (>>) operator
behaves differently for unsigned
and signed numbers:
•Unsigned numbers are
logically-right shifted (by
shifting in 0s, always)
•Signed numbers are
arithmetically-right shifted (by
shifting in the sign bit)