In the following code when I arithmetically right shift MSB3 (which happens to be 0) by 31 I get 2.
But when I replace MSB3 by 0 I get 0, which is the result I was expecting in the first case.
Why does this happen?
const int value = 0; //This happens after adding 0x80000000 to 0x80000000
const int mask = 0x1;
const int mask2 = mask << 31;
const int MSB3 = value & mask2; // MSB3 = 0
const int trueMSB3 = (MSB3 >> 31) // This gives 2 rather than 0???
const int trueMSB3 = (0 >> 31) //Gives 0
If you have 64-bit int
s then this is not possible as you have described it; since shifting 0
always gives 0
. The "real code" must be different to what you have posted.
If you have 32-bit int
then your program already caused undefined behaviour by doing mask << 31
. Shifting into the sign bit causes UB. The result of this is that anything can happen; including subsequent code printing 2
, or missiles being launched.
Your first comment indicates that maybe the "real code" did not have const int value = 0;
, but some other code which you describe. It would be better to post the real code. That code may also have undefined behaviour, judging by your description.
To get well-defined results when doing shifts, use unsigned integers instead. To get better help, update your posted code to be a MCVE and include which compiler and system you are on.
User contributions licensed under CC BY-SA 3.0