[BangPypers] Need help understanding -9 >> 1
steve at lonetwin.net
Mon Jul 2 13:59:42 CEST 2012
On 06/29/2012 04:03 PM, Anand Chitipothu wrote:
> 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.
btw, one doesn't need to use ctypes for this. Just coincidentally, a while back
I was wondering why I couldn't use the builtin hex() to represent negative
numbers in python and learned that one has to limit the integer to 32 bits for
this to work correctly. ie:
>>> hex(-9 & 0xffffffff)
I got this from :
random spiel: http://lonetwin.net/
what i'm stumbling into: http://lonetwin.stumbleupon.com/
More information about the BangPypers