1

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.

Barmar
  • 741,623
  • 53
  • 500
  • 612
JakeGreen
  • 89
  • 5

2 Answers2

6

You want the binascii module.

>>> binascii.hexlify('\x01\x25\x89')
'012589'
>>> binascii.hexlify('\x25\x01\x00\x89')
'25010089'
Chris
  • 1,657
  • 1
  • 13
  • 20
5

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'
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
  • This works well for python 2 and I like that it doesn't require a module. The answer by [Chris](http://stackoverflow.com/a/34661666/4538876) will work for python 2 and 3 though. – JakeGreen Jan 07 '16 at 18:02
  • @JakeGreen, neither would actually work for python3 without an encode, if you wanted a solution for both 2 and 3 `codecs.encode(s, "hex")` but again you will have to encode s – Padraic Cunningham Jan 07 '16 at 18:05
  • you are right. I was thinking more about my specific use case in my previous comment and I never mentioned what my use case is. I have been using `struct` to pack some data which returns type bytes in python 3 and not a string, so binascii works for my use case in both versions of python. Sorry about that. Thanks for the good info though. – JakeGreen Jan 07 '16 at 18:36