[Python] bytes and hex string conversion.
repeatedly played around with the assembly parsing and readable printing of code streams in several environments, always encountering hex string and bytes conversion, recorded here.
- on python 2.7.x (which is really hard to handle in older environments), the hex string is converted between bytes like this:
>>> a = 'aabbccddeeff'
>>> a_bytes = a.decode('hex')
>>> print(a_bytes)
b'\xaa\xbb\xcc\xdd\xee\xff'
>>> aa = a_bytes.encode('hex')
>>> print(aa)
aabbccddeeff
>>>
- in python 3 environment, because the implementation of string and bytes has changed significantly, this conversion can no longer be completed with encode/decode.
2.1 before python3.5, one way of doing this conversion was to look like this:
>>> a = 'aabbccddeeff'
>>> a_bytes = bytes.fromhex(a)
>>> print(a_bytes)
b'\xaa\xbb\xcc\xdd\xee\xff'
>>> aa = ''.join(['%02x' % b for b in a_bytes])
>>> print(aa)
aabbccddeeff
>>>
2.2 after python 3.5, you can do the following:
>>> a = 'aabbccddeeff'
>>> a_bytes = bytes.fromhex(a)
>>> print(a_bytes)
b'\xaa\xbb\xcc\xdd\xee\xff'
>>> aa = a_bytes.hex()
>>> print(aa)
aabbccddeeff
>>>
last
data = b'\x820\xb100\x03\xc3\xb4'
print('type(data) = ', type(data))
#type(data) = <class 'bytes'>
lst = list(data)
print(lst)
print(type(lst[0]))
#[130, 48, 177, 48, 48, 3, 195, 180]
#<class 'int'>
tmp = data.hex()
print(type(tmp), tmp)
# <class 'str'> 8230b1303003c3b4
strr = '8230b1303003c3b4'
num = bytes.fromhex(strr)
print(type(num), num)
# <class 'bytes'> b'\x820\xb100\x03\xc3\xb4'
div>