tags:

views:

936

answers:

2
+9  A: 

This will do the trick:

>>> print hex (-1 & 0xffffffff)
0xffffffffL

or, in function form (and stripping off the trailing "L"):

>>> def hex2(n):
...     return hex (n & 0xffffffff)[:-1]
...
>>> print hex2(-1)
0xffffffff
>>> print hex2(17)
0x11

or, a variant that always returns fixed size (there may well be a better way to do this):

>>> def hex3(n):
...     return "0x%s"%("00000000%s"%(hex(n&0xffffffff)[2:-1]))[-8:]
...
>>> print hex3(-1)
0xffffffff
>>> print hex3(17)
0x00000011

Or, avoiding the hex() altogether, thanks to Ignacio and bobince:

def hex2(n):
    return "0x%x"%(n&0xffffffff)

def hex3(n):
    return "0x%s"%("00000000%x"%(n&0xffffffff))[-8:]
paxdiablo
.. or it would if I were less dyslexic ..
Ellery Newcomer
Don't rely on the 'L' suffix, it is going away in Python 3.0 so hex2 will chop off a digit. The %x formatting operator is generally a better bet than hex().
bobince
Incorporated comment and Ignacios option below into accepted answer (and gave Ignacio an upvote)
paxdiablo
+3  A: 
'%#4x' % (-1 & 0xffffffff)
Ignacio Vazquez-Abrams