Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print a signed integer as hexadecimal number in two's complement with python?

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..."

like image 929
none Avatar asked Jul 13 '10 08:07

none


People also ask

How do you convert a number to hexadecimal in Python?

hex() function is one of the built-in functions in Python3, which is used to convert an integer number into it's corresponding hexadecimal form. Syntax : hex(x) Parameters : x - an integer number (int object) Returns : Returns hexadecimal string.

How do you convert to 2's complement in Python?

The way to compute the Two's complement is by taking the One's complement and adding 1 . 1111 1100 would then be -12 in Two's complement. The advantage over One's complement is that there isn't a duplicate representation of 0 with 0000 0000 and 1111 1111 , hence allowing one more value to be represented -128 .

How do you get 2's complement of a binary number in Python?

Use the syntax int("{0:0nb}". format(number))" with n as the number of bits to convert number into an n bit number via string formatting. To flip the bits of the binary number, use the syntax ~ bits with bits as the binary number. Add 1 to this number to get the two's complement of the number.


2 Answers

Simple

>>> hex((-4) & 0xFF)
'0xfc'
like image 60
siu Avatar answered Sep 27 '22 16:09

siu


>>> x = -123
>>> bits = 16
>>> hex((1 << bits) + x)
'0xff85'
>>> bits = 32
>>> hex((1 << bits) + x)
'0xffffff85'
like image 26
John La Rooy Avatar answered Sep 27 '22 17:09

John La Rooy