Is there a reasonably simple way to convert from a hex integer to a hex string in python?
For example, I have 0xa1b2c3 and I want "0xa1b2c3". If I use str(), it automatically gets converted to base 10, and then I can't convert it back because it's a string at that point.
2 Answers
Why not just do hex()?
>>> testNum = 0xa1b2c3
>>> hex(testNum)
'0xa1b2c3'
>>> test = hex(testNum)
>>> isinstance(test, str)
True
hex returns a string representation. See help(hex)
hex(...)
hex(number) -> string
Return the hexadecimal representation of an integer or long integer.
Comments
Use hex:
>>> x = 0xa1b2c3
>>> hex(x)
'0xa1b2c3'
>>> "{:#x}".format(x)
'0xa1b2c3'
or format:
>>> format(x, '#x')
'0xa1b2c3'
2 Comments
Martijn Pieters
Use the
format() function instead; format(x, '#x'). No need to have the overhead of the string format parsing too.Morgan Barksdale
Thanks. It seems like you both answered the same thing at the same time, so I'm accepting his answer because he has a lot less reputation points than you. Cheers