Reputation: 89
I am looking for a good way to convert a string into a hex string.
For example:
'\x01\x25\x89'
-> '0x012589'
'\x25\x01\x00\x89'
-> '0x25010089'
Here is what I have come up with:
def to_hex(input_str):
new_str = '0x'
for char in input_str:
new_str += '{:02X}'.format(ord(char))
return new_str
It seems like there is probably a better way to do this that I haven't been able to find yet.
Upvotes: 1
Views: 734
Reputation: 180391
Just encode to hex:
In [5]: s= "\x01\x25\x89"
In [6]: s.encode("hex")
Out[6]: '012589'
In [7]: s = "\x25\x01\x00\x89"
In [8]: s.encode("hex")
Out[8]: '25010089'
Upvotes: 5