views:

210

answers:

4

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?

+15  A: 

What about this?

int sign = number < 0;

Noctis Skytower
+3  A: 

The >> operator is performing an arithmetic shift, which retains the sign of the number.

LukeH
No. What kind of shift is performed by `>>` operator is implementation-defined. Could be any kind of shift.
AndreyT
@AndreyT: I said "the `>>` operator is performing an arithmetic shift", and that's exactly what it is doing in this case, judging by the OP's description. Notice that I *did not* say "the `>>` operator always performs an arithmetic shift" or anything like that. Perhaps I should have been more explicit, but either way, I don't think my answer deserves a downvote.
LukeH
+4  A: 

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, whihch 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.

AndreyT
+2  A: 

Because you are shifting signed integer. Cast the integer to unsigned:

int sign_bit = ((unsigned int)number) >> 31;
Paja