python - python - 当附加了字节标记时,如何在python中将字节转换为整数?
问题描述
我在 python 中有一个函数,它读取串行端口缓冲区中的前 3 个字节。然后我想将第三个字节转换为一个整数,这将允许我确定总字节数组的长度。但是,当我使用时,出现int()
以下错误:
ValueError: invalid literal for int() with base 16: b'\x16'
我已经尝试将字符串进一步切片,但这只会返回 b''。如何将字节转换为整数?
谢谢!
解决方案
使用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
推荐阅读
- python - 使用 grep 或 awk 仅提取 4 天的行
- python - 在 Django 项目中动态设置“默认”数据库
- c# - 具有相同基本接口但两个约束不能相同的两个约束
- python - 如何用另一个数据框替换部分数据框
- sas - Biderectional Vlookup - 同一张表中的标志 - Sas
- geojson - 使用topomerge合并topojson会打乱缠绕顺序
- linux - docker-compose 不能使用 .env 中的变量
- python - 如何一次更换多个项目?[Python]
- python - 测量网络质量
- c# - 如何为使用 Rotativa 生成动态内容的 PDF 生成页脚