400

What's the correct way to convert bytes to a hex string in Python 3?

I see claims of a bytes.hex method, bytes.decode codecs, and have tried other possible functions of least astonishment without avail. I just want my bytes as hex!

2

9 Answers 9

761

Since Python 3.5 this is finally no longer awkward:

>>> b'\xde\xad\xbe\xef'.hex()
'deadbeef'

and reverse:

>>> bytes.fromhex('deadbeef')
b'\xde\xad\xbe\xef'

works also with the mutable bytearray type.

Reference: https://docs.python.org/3/library/stdtypes.html#bytes.hex

1
  • 19
    bytes.fromhex() is also available on Python 3.0+ (not just 3.5+). bytes.hex() is only on Python 3.5+.
    – johnthagen
    Commented Jun 13, 2018 at 14:16
110

Use the binascii module:

>>> import binascii
>>> binascii.hexlify('foo'.encode('utf8'))
b'666f6f'
>>> binascii.unhexlify(_).decode('utf8')
'foo'

See this answer: Python 3.1.1 string to hex

7
  • 11
    This is good. Mind boggling is that you can convert hex to bytes using bytes.fromhex(hex_str), but you cannot convert bytes to hex using bytes.tohex() - what is the rational in this?
    – nagylzs
    Commented Nov 16, 2013 at 21:57
  • 1
    I guess the relationship between bytes and hex isn't a property of either (which doesn't answer why fromhex is there). Seems like it wasn't just an oversight but something that was argued over: bugs.python.org/issue3532#msg70950. Q: Would it hurt to have the tohex method of the bytes object to perform this task as well? A: IMO, yes, it would. It complicates the code, and draws the focus away from the proper approach to data conversion (namely, functions - not methods).
    – Mu Mind
    Commented Nov 17, 2013 at 1:42
  • 6
    Does this really answer the question? It doesn't return a hex str but a bytes. I know that the OP seems happy with the answer but won't be better to expand this answer to include .decode("ascii") also to convert it to a "string" Commented Jun 8, 2015 at 17:11
  • 4
    I was thinking that many people land on this question/answer looking for a way to printout a bytes. If you print(b'666f6f') you get the b in the printout. If you .decode("ascii") then you don't. Just thinking on how those that actually had a bytes (true binary with items > 128 , not an ascii string) an wanted to printout it. Commented Jun 9, 2015 at 5:52
  • 9
    @nagylzs: there is .hex() method in Python 3.5+
    – jfs
    Commented Feb 24, 2016 at 15:39
54

Python has bytes-to-bytes standard codecs that perform convenient transformations like quoted-printable (fits into 7bits ascii), base64 (fits into alphanumerics), hex escaping, gzip and bz2 compression. In Python 2, you could do:

b'foo'.encode('hex')

In Python 3, str.encode / bytes.decode are strictly for bytes<->str conversions. Instead, you can do this, which works across Python 2 and Python 3 (s/encode/decode/g for the inverse):

import codecs
codecs.getencoder('hex')(b'foo')[0]

Starting with Python 3.4, there is a less awkward option:

codecs.encode(b'foo', 'hex')

These misc codecs are also accessible inside their own modules (base64, zlib, bz2, uu, quopri, binascii); the API is less consistent, but for compression codecs it offers more control.

2
  • 1
    using python 3.3: LookupError: unknown encoding: hex Commented Mar 5, 2014 at 22:37
  • 1
    @JanusTroelsen: try 'hex_codec'. Or just use binascii.hexlify(b'foo') directly
    – jfs
    Commented Mar 18, 2014 at 8:04
34

New in python 3.8, you can pass a delimiter argument to the hex function, as in this example

>>> value = b'\xf0\xf1\xf2'
>>> value.hex('-')
'f0-f1-f2'
>>> value.hex('_', 2)
'f0_f1f2'
>>> b'UUDDLRLRAB'.hex(' ', -4)
'55554444 4c524c52 4142'

https://docs.python.org/3/library/stdtypes.html#bytes.hex

1
  • 1
    This can be useful: [f'0x{val}' for val in value.hex(' ', 2).split()] gives something like ['0x2600', '0x9c00', '0x1900', '0x0c75'] Commented Apr 28, 2022 at 14:10
12

The method binascii.hexlify() will convert bytes to a bytes representing the ascii hex string. That means that each byte in the input will get converted to two ascii characters. If you want a true str out then you can .decode("ascii") the result.

I included an snippet that illustrates it.

import binascii

with open("addressbook.bin", "rb") as f: # or any binary file like '/bin/ls'
    in_bytes = f.read()
    print(in_bytes) # b'\n\x16\n\x04'
    hex_bytes = binascii.hexlify(in_bytes) 
    print(hex_bytes) # b'0a160a04' which is twice as long as in_bytes
    hex_str = hex_bytes.decode("ascii")
    print(hex_str) # 0a160a04

from the hex string "0a160a04" to can come back to the bytes with binascii.unhexlify("0a160a04") which gives back b'\n\x16\n\x04'

7
import codecs
codecs.getencoder('hex_codec')(b'foo')[0]

works in Python 3.3 (so "hex_codec" instead of "hex").

1
  • Perhaps interestingly, in Python 3.4 "hex" or "hex_codec" works fine. Commented Dec 24, 2014 at 9:08
6

it can been used the format specifier %x02 that format and output a hex value. For example:

>>> foo = b"tC\xfc}\x05i\x8d\x86\x05\xa5\xb4\xd3]Vd\x9cZ\x92~'6"
>>> res = ""
>>> for b in foo:
...     res += "%02x" % b
... 
>>> print(res)
7443fc7d05698d8605a5b4d35d56649c5a927e2736
2
  • According to me, it is the best answer because it works with every Python version and does not need any import. Yet, I would better display hexa strings in upper case res.upper()
    – Bruno L.
    Commented Apr 28, 2020 at 18:24
  • No need for upper()!. You can control case by x or X: '%02X' % 79 == '4F'
    – vav
    Commented May 19, 2023 at 15:21
4

OK, the following answer is slightly beyond-scope if you only care about Python 3, but this question is the first Google hit even if you don't specify the Python version, so here's a way that works on both Python 2 and Python 3.

I'm also interpreting the question to be about converting bytes to the str type: that is, bytes-y on Python 2, and Unicode-y on Python 3.

Given that, the best approach I know is:

import six

bytes_to_hex_str = lambda b: ' '.join('%02x' % i for i in six.iterbytes(b))

The following assertion will be true for either Python 2 or Python 3, assuming you haven't activated the unicode_literals future in Python 2:

assert bytes_to_hex_str(b'jkl') == '6a 6b 6c'

(Or you can use ''.join() to omit the space between the bytes, etc.)

1
  • I've found this useful when supporting Python 3.7, which does not have a sep arg in bytes.hex. At time of writing, 3.7 is still a supported version.
    – theY4Kman
    Commented Mar 2, 2023 at 17:11
1

If you want to convert b'\x61' to 97 or '0x61', you can try this:

[python3.5]
>>>from struct import *
>>>temp=unpack('B',b'\x61')[0] ## convert bytes to unsigned int
97
>>>hex(temp) ##convert int to string which is hexadecimal expression
'0x61'

Reference:https://docs.python.org/3.5/library/struct.html

2
  • Somehow helps me with esp32
    – Tejas Tank
    Commented Apr 6, 2020 at 19:56
  • Absolutly, as @TejasTank says. This only method working on MicroPhyton where a lot of libraries are not available.
    – leosok
    Commented Apr 2, 2021 at 0:21

Not the answer you're looking for? Browse other questions tagged or ask your own question.