首页 > 解决方案 > python - 当附加了字节标记时,如何在python中将字节转换为整数?

问题描述

我在 python 中有一个函数,它读取串行端口缓冲区中的前 3 个字节。然后我想将第三个字节转换为一个整数,这将允许我确定总字节数组的长度。但是,当我使用时,出现int()以下错误:

ValueError: invalid literal for int() with base 16: b'\x16'

我已经尝试将字符串进一步切片,但这只会返回 b''。如何将字节转换为整数?

谢谢!

标签: pythonpython-3.xintegerhexbyte

解决方案


使用int.from_bytes().

>>>int.from_bytes(b'\x00\x10', byteorder='big')

16

>>>int.from_bytes(b'\x00\x10', byteorder='little')

4096

>>>int.from_bytes(b'\xfc\x00', byteorder='big', signed=True)

-1024

>>>int.from_bytes(b'\xfc\x00', byteorder='big', signed=False)

64512

>>>int.from_bytes([255, 0, 0], byteorder='big')

16711680


推荐阅读