C++ – How to access the sign bit of a number in C++

binarybitwise-operatorsc

I want to be able to access the sign bit of a number in C++. My current code looks something like this:

int sign bit = number >> 31;

That appears to work, giving me 0 for positive numbers and -1 for negative numbers. However, I don't see how I get -1 for negative numbers: if 12 is

0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 1100

then -12 is

1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 0011

and shifting it 31 bits would make

0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0001

which is 1, not -1, so why do I get -1 when I shift it?

Best Answer

What about this?

int sign = number < 0;

Related Topic