You are not logged in.
Doing a right bitshift on +5 gives me +2 which is logical to me:
0101 => 0010
However using a negative number -5 results in -3:
-0101 => -0011 ???
Can someone explain why the last zero flipped to a one instead?
chrishir@bra ~/Desktop/test $ cat test.cpp
#include <stdlib.h>
#include <iostream>
int main()
{
int x = -5;
int y = x >> 1;
std::cout << x << std::endl;
std::cout << y << std::endl;
}
chrishir@bra ~/Desktop/test $ ./test.bin
-5
-3
chrishir@bra ~/Desktop/test $
Last edited by toffyrn (2010-10-27 08:05:08)
Offline
Negative numbers are represented using two's complement:
-5 = 1011 (bit patterns obviously truncated, but all the missing bits are '1's)
-3 = 1101
When bit shifting a signed value, the sign bit is preserved. Hence, bit shifting the -3 right by one would give -2 (1110), and again would give -1 (1111).
Last edited by Barrucadu (2010-10-27 07:59:08)
Offline
Thanks...
So my understanding of how negative numbers are stored was wrong.
I understood it now
Last edited by toffyrn (2010-10-27 08:06:39)
Offline
Actually, C and C++ don't guarantee that two's complement is used to represent signed integers, but they do guarantee that the result of shifting a signed number to the right is always rounded down (towards negative infinity).
Offline