Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print bytes to hex

I want to encode string to bytes.

To convert to byes, I used byte.fromhex()

>>> byte.fromhex('7403073845')
b't\x03\x078E'

But it displayed some characters.

How can it be displayed as hex like following?

b't\x03\x078E' => '\x74\x03\x07\x38\x45'
like image 356
hyde1004 Avatar asked Mar 13 '23 15:03

hyde1004


1 Answers

I want to encode string to bytes.

bytes.fromhex() already transforms your hex string into bytes. Don't confuse an object and its text representation -- REPL uses sys.displayhook that uses repr() to display bytes in ascii printable range as the corresponding characters but it doesn't affect the value in any way:

>>> b't' == b'\x74'
True

Print bytes to hex

To convert bytes back into a hex string, you could use bytes.hex method since Python 3.5:

>>> b't\x03\x078E'.hex()
'7403073845'

On older Python version you could use binascii.hexlify():

>>> import binascii
>>> binascii.hexlify(b't\x03\x078E').decode('ascii')
'7403073845'

How can it be displayed as hex like following? b't\x03\x078E' => '\x74\x03\x07\x38\x45'

>>> print(''.join(['\\x%02x' % b for b in b't\x03\x078E']))
\x74\x03\x07\x38\x45
like image 109
jfs Avatar answered Mar 18 '23 12:03

jfs