[BangPypers] Need help understanding -9 >> 1
anandology at gmail.com
Fri Jun 29 12:33:54 CEST 2012
On Fri, Jun 29, 2012 at 3:40 PM, Varun Narang <varunarang at gmail.com> wrote:
> Hi all,
> I need some help understanding the right shift operation on -9. To my
> understanding, it's represented as -0b1001, Now, if I shift it one place to
> right, it should give me -0b0100, which is decimal equivalent of 4. but
> running this on python console gives me -5.
> Please help me out here.
-9 is represented internally as 0xFFFFFFF7.
The last byte in binary is 11110111. When on rightshift, it becomes
11111011. Which is 0xFFFFFFFB, hex representation of -5.
Try this to see how -9 and -5 are represented internally:
>>> import ctypes
>>> libc = ctypes.CDLL("libc.so.6")
>>> a = libc.printf("%x\n", -9)
>>> a = libc.printf("%x\n", -5)
This works only on linux.
Read https://en.wikipedia.org/wiki/Signed_number_representations how
negative integers are represented internally.
More information about the BangPypers