python decimal integer to hexadecimal bytes

python decimal integer to hexadecimal bytes

Used in serial port sending, input decimal array, output hexadecimal

a = [1,3,4,5,6,7,8]
b = bytes(a).hex()
data = bytes.fromhex(b)

output

b'\x01\x03\x04\x05\x06\x07\x08'

1. Decimal to hexadecimal

Decimal and hexadecimal conversions use hex()and int().

>>> a = 11
>>> b = hex(a)
>>> b
'0xb'
>>> type(a)
<class 'int'>
>>> type(b)
<class 'str'>

a is an integer, converted to hexadecimal b is a string

>>> b = 0x11
>>> a = int(b)
>>> a
17
>>> type(a)
<class 'int'>
>>> type(b)
<class 'int'>

Among them, a and b are integers.

2.hex and fromhex in bytes

  • hex: Convert the value of bytes to fromstr.

Input an integer array and get a hexadecimal string

>>> a = [0,1,2,3,4,5]
>>> bytes(a).hex()
'000102030405'
>>> type(bytes(a).hex())
<class 'str'>		# 输出是字符串

As for why it is bytes(a).hex()written like this, I don’t understand, but I tried it.

>>> a = [1,2,3,4,5,6]
>>> b = bytes.hex(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: descriptor 'hex' for 'bytes' objects doesn't apply to a 'list' object 	# hex的参数应该是bytes,所以报错了。
>>> b = bytes(a)
>>> c = bytes.hex(b)
>>> c		# 首先将数组转成bytes,然后再用这个函数,可以正常打印
'010203040506'
>>> c= hex(b)		#直接用hex()函数将bytes转16进制也不行,hex()的输入必须是整数
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'bytes' object cannot be interpreted as an integer
  • fromhex: Convert the value of fromstr to hex

Input a hexadecimal string and get the output of hexadecimal bytes with \x

>>> b = '000102030405'
>>> bytes.fromhex(b)
b'\x00\x01\x02\x03\x04\x05'
>>> type(b)
<class 'str'>
>>> type(bytes.fromhex(b))
<class 'bytes'> 	# 输出是bytes

3. supplement

  • encode and decode in python

encode is encoding, decode is decoding

  • encode() converts strings to bytes
  • decode() decodes the bytes type into a string

Guess you like

Origin blog.csdn.net/qq_43418888/article/details/129372457