Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

negative integer number >> 31 = -1 not 1? [duplicate]

Tags:

c

so, lets say I have a signed integer (couple of examples):

-1101363339 = 10111110 01011010 10000111 01110101 in binary.
-2147463094 = 10000000 00000000 01010000 01001010 in binary.
-20552      = 11111111 11111111 10101111 10111000 in binary.

now: -1101363339 >> 31 for example, should equal 1 right? but on my computer, I am getting -1. Regardless of what negative integer I pick if x = negative number, x >> 31 = -1. why? clearly in binary it should be 1.

like image 792
dgamma3 Avatar asked Jun 21 '13 00:06

dgamma3


2 Answers

Per C99 6.5.7 Bitwise shift operators:

If E1 has a signed type and a negative value, the resulting value is implementation-defined.

where E1 is the left-hand side of the shift expression. So it depends on your compiler what you'll get.

like image 60
Jeff Walden Avatar answered Oct 17 '22 07:10

Jeff Walden


In most languages when you shift to the right it does an arithmetic shift, meaning it preserves the most significant bit. Therefore in your case you have all 1's in binary, which is -1 in decimal. If you use an unsigned int you will get the result you are looking for.

Per C 2011 6.5.7 Bitwise shift operators:

The result of E1 >> E2 is E1 right-shifted E2 bit positions. If E1 has an unsigned type or if E1 has a signed type and a nonnegative value, the value of the result is the integral part of the quotient of E1/ 2E2. If E1 has a signed type and a negative value, the resulting value is implementation-defined.

Basically, the right-shift of a negative signed integer is implementation defined but most implementations choose to do it as an arithmetic shift.

like image 36
aaronman Avatar answered Oct 17 '22 07:10

aaronman