How can I access the sign bit of a number in C++?
What about this?
int sign = number < 0;
The result of right-shifting a negative number in C++ is implementation-defined. So, no one knows what right-shifting your -12
should get on your specific platform. You think it should make the above (1
), while I say that it can easily produce all-ones pattern, which is -1
. The latter is called sign-extended shifting. In sign-extended shifting the sign bit is copied to the right, but never shifted out of its place.
If all you are interested in is the value of the sign bit, then stop wasting time trying to use bitwise operations, like shifts etc. Just compare your number to 0 and see whether it is negative or not.