[BangPypers] Need help understanding -9 >> 1

steve steve at lonetwin.net
Mon Jul 2 13:59:42 CEST 2012


Hi,

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)
> fffffff7
>>>> a = libc.printf("%x\n", -5)
> fffffffb
> 
> 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)
'0x9'
>>> hex(-9)
'-0x9'
>>> hex(-9 & 0xffffffff)
'0xfffffff7'
>>>

I got this from :
http://stackoverflow.com/questions/3831833/printing-negative-values-as-hex-in-python

cheers,
- steve

-- 
random spiel: http://lonetwin.net/
what i'm stumbling into: http://lonetwin.stumbleupon.com/


More information about the BangPypers mailing list