python 10进制整数转16进制bytes

python 10进制整数转16进制bytes

用在串口发送,输入10进制数组,输出16进制

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

输出

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

1.10进制转16进制

10进制和16进制转化用的是hex()int()

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

a 是整型,转成16进制b是字符串

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

其中,a和b都是整型。

2.bytes中的hex 和fromhex

  • hex:将bytes的值转化为fromstr。

输入一个整数数组,得到一个16进制的字符串

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

至于为什么要用bytes(a).hex()这么写,不懂,但是做了尝试。

>>> 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:将fromstr的值转化为hex

输入16进制字符串,得到带\x的16进制bytes输出

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

3.补充

  • python中encode和decode

encode是编码,decode是解码

  • encode()将字符串转换成bytes类型
  • decode()将bytes类型解码成字符串

猜你喜欢

转载自blog.csdn.net/qq_43418888/article/details/129372457