Ash*_*hok 6 python binary struct python-3.x
我正在尝试在 Python 3.8 中解压 python 结构并收到错误
类型错误:需要一个类似字节的对象,而不是“int”
. 相同的代码在 Python 2.7 中运行良好
import struct
hexval= b'J\xe6\xe7\xa8\x002\x10k\x05\xd4\x7fA\x00\x04\n\x90\x1a\n'
aaT = struct.unpack('>H',hexval[4:6])
aa = aaT[0]
print("aa",aa)
bbT = struct.unpack(">B",hexval[12])
bb = bbT[0]&0x3 # just lower 2 bits
print("bb",bb)
Run Code Online (Sandbox Code Playgroud)
输出:
氨基酸 50
回溯(最近一次调用最后一次):文件“./sample.py”,第 9 行,在 bbT = struct.unpack(">B",hexval[12]) 类型错误:需要一个类似字节的对象,而不是 'int '
当我转换为字节时
我得到这样的错误。
回溯(最近一次调用):文件“sample.py”,第 9 行,在 bbT = struct.unpack(">B",bytes(hexval[12])) struct.error: unpack requires a buffer of 1 bytes
我怎样才能解压这个二进制数据
这是与从 Python 2 到 3 的数据类型相关的另一项更改。原因在“ Why do I get an int when I index bytes?”的答案中进行了解释。
以防万一答案不明显,要获得与 Python 2 相同的结果,请执行以下操作:
bbT = struct.unpack(">B",hexval[12:13]) # slicing a byte array results in a byte array, same as Python 2
Run Code Online (Sandbox Code Playgroud)