Is this the best way to convert a Python number to a hex string?
number = 123456789
hex(number)[2:-1].decode('hex')
Sometimes it doesn't work and complains about Odd-length string when you do 1234567890.
Clarification:
I am going from int to hex.
Also, I need it to be escaped.
IE: 1234567890 -> '\x49\x96\x02\xd2' not '499602D2'
Also, it needs to be able to take any Python integer. IE. something larger than an Int.
Edit:
Here is the best solution so far I have cobbled together from Paolo and Devin's post.
def hexify(num):
num = "%x" % num
if len(num) % 2:
num = '0'+num
return num.decode('hex')
You can use string formatting:
>>> number = 123456789
>>> hex = "%X" % number
>>> hex
'75BCD15'
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