JakeGreen
JakeGreen

Reputation: 89

Converting string into hex representation

I am looking for a good way to convert a string into a hex string.

For example:

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

Answers (2)

Padraic Cunningham
Padraic Cunningham

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

Chris
Chris

Reputation: 1697

You want the binascii module.

>>> binascii.hexlify('\x01\x25\x89')
'012589'
>>> binascii.hexlify('\x25\x01\x00\x89')
'25010089'

Upvotes: 6

Related Questions