[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>
Read More:
- Python conversion hex to string, high and low data processing
- python reads csv file is an error _csv.Error: iterator should return strings, not bytes (did you open the file in text)
- How to Split numbers and strings in a strings
- ‘Conversion failed when converting date and/or time from character string.DB-Lib error message 241,
- Java uses regular expressions to intercept the contents between specified strings
- Attributeerror: ‘bytes’ object has no attribute’ encode ‘
- 43. Implementation of the shortest code of multiply strings | Java
- How to replace strings in VIM
- Python: crawler handles strings of XML and HTML
- Shell removes double quotes from strings
- Java lossy conversion
- Conversion between list and string array
- No matching editors or conversion strategy found
- Error report of covertotraditional conversion from simplified to traditional
- Conversion from hexadecimal to decimal
- [jQuery] jQuery operates on JSON strings or JSON objects
- Local date time conversion in java8
- The pyinstaller settings icon appears“ struct.error : unpack requires a buffer of 16 bytes”
- [solution] Python flash database migrate error type error: option values must be strings
- python ValueError: source code string cannot contain null bytes