views:

73

answers:

5

I have a negative integer (4 bytes) of which I would like to have the hexadecimal form of its two's complement representation.

>>> i = int("-312367")
>>> "{0}".format(i)
'-312367'
>>> "{0:x}".format(i)
'-4c42f'

But I would like to see "FF..."

+1  A: 

Here's a way (for 16 bit numbers):

>>> x=-123
>>> hex(((abs(x) ^ 0xffff) + 1) & 0xffff)
'0xff85'

(Might not be the most elegant way, though)

adamk
Thanks! (use abs(x))
none
+1  A: 

See if this answer to a related question is what you're looking for: http://stackoverflow.com/questions/1604464/twos-complement-in-python/1605553#1605553

sarnold
Yes, bitstrings hex property seems to return what I need as well. Thanks.
none
+2  A: 

Using the bitstring module:

>>> bitstring.Bits('int:32=-312367').hex
'0xfffb3bd1'
Scott Griffiths
+1  A: 
>>> x=123
>>> bits=16
>>> hex((1<<bits)-x)
'0xff85'
>>> bits=32
>>> hex((1<<bits)-x)
'0xffffff85'
gnibbler
A: 

The struct module performs conversions between Python values and C structs represented as Python bytes objects. The packed bytes object offers access to individual byte values. This can be used to display the underlying (C) integer representation.

>>> packed = struct.pack('>i',i) # big-endian integer
>>> type(packed)
<class 'bytes'>
>>> packed
b'\xff\xfb;\xd1'
>>> "%X%X%X%X" % tuple(packed)
'FFFB3BD1'
>>> 
gimel