SoFunction
Updated on 2024-11-10

Converting between bytes and HexStr in Python3

When manipulating data content in Python, most of the time you may encounter the following 3 types of data processing:

hexstring e.g. '1C532145697A8B6F'

str e.g. '\x1C\x53\x21\x45\x69\x7A\x8B\x6F'

list e.g. [0x1C, 0x53, 0x21, 0x45, 0x69, 0x7A, 0x8B, 0x6F]

There may be cases where you need to switch back and forth between these 3 types of data due to type inconsistencies in various third-party modules (e.g. pyDes), or in interfaces you write yourself.

The core of the methods that need to be used are as follows:

list() converts an object to a list

str() converts the object to str

bytearray() converts an object to a bytearray

() converts an object from hexstring to bytearray

binascii.b2a_hex() convert object from str to hexstring

1. Integral list to str

E.g. [0x53, 0x21, 0x6A] -> '\x53\x21\x6a'

Methods: list -> bytearray -> str

x = [0x53, 0x21, 0x6A] 
y = str(bytearray(x)) 

2. str to shaping list

E.g. '\x53\x21\6a' -> [0x53, 0x21, 0x6A]

Method: Character-by-character to decimal conversion

x = '\x53\x21\x6a' 
y = [ord(c) for c in x] 

3. Plastic list converted to hex string

E.g. [0x53, 0x21, 0x6A] -> '53216A'

Methods: list -> bytearray -> str -> hexstring

import binascii 
x = [0x53, 0x21, 0x6A] 
y = str(bytearray(x)) 
z = binascii.b2a_hex(y) 

4. hex string to shaped list

E.g. '53216A' -> [0x53, 0x21, 0x6A]

Methods: hexstring -> bytearray -> list

x = '53216A' 
y = (x) 
z = list(y) 

5. hex string to str

E.g.: '53216A' -> '\x53\x21\x6A'

Methods: hexstring -> bytearray -> str

x = '53216A' 
y = (x) 
z = str(y) 

Above this article on Python3 bytes and HexStr conversion between the details is all that I have shared with you, I hope to give you a reference, and I hope you support me more.