Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 412
Matt Joiner Avatar asked Jul 08 '11 12:07

Matt Joiner


People also ask

How do you convert bytes to hexadecimal?

To convert a byte to hexadecimal equivalent, use the toHexString() method in Java. Firstly, let us take a byte value. byte val1 = (byte)90; Before using the method, let us do some more manipulations.

Can you convert string to hex in Python?

To convert Python String to hex, use the inbuilt hex() method. The hex() is a built-in method that converts the integer to a corresponding hexadecimal string. For example, use the int(x, base) function with 16 to convert a string to an integer.


2 Answers

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

like image 157
Felix Weis Avatar answered Sep 28 '22 00:09

Felix Weis


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

like image 22
Mu Mind Avatar answered Sep 28 '22 01:09

Mu Mind