Say I have the classic 4-byte signed integer, and I want something like
print hex(-1)
to give me something like
0xffffffff
In reality, the above gives me -0x1
. I'm dawdling about in some lower level language, and python commandline is quick n easy.
So.. is there a way to do it?
An integer can be converted to a hexadecimal by using the string. ToString() extension method. int. Parse − Converts the string representation of a number to its 32-bit signed integer equivalent.
atoi(s[,base]) converts a string into an integer. The default is decimal, but you can specify octal 8, hexadecimal 16, or decimal 10.
Use base=16 as a second argument of the int() function to specify that the given string is a hex number. The int() function will then convert the hex string to an integer with base 10 and return the result.
This will do the trick:
>>> print(hex (-1 & 0xffffffff))
0xffffffff
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:]
Try this function:
'%#4x' % (-1 & 0xffffffff)
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