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..."
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.
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 .
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.
Simple
>>> hex((-4) & 0xFF)
'0xfc'
>>> x = -123
>>> bits = 16
>>> hex((1 << bits) + x)
'0xff85'
>>> bits = 32
>>> hex((1 << bits) + x)
'0xffffff85'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With