我正在尝试使用 struct.pack 将 python bytearray 的内容打包为 4byte 有符号整数。不幸的是,pack 想要一个字符串,所以经过一番谷歌搜索后,我认为我需要将字节数组解码为字符串。我认为 ascii 的意思是“since”,因为 ascii 字符是一个字节长。不幸的是,ascii 不想支持我的值 > 127,所以我想我会使用替换...
但是当我这样做时,解码会返回一个 unicode 类型的对象,现在我的每个字节都是一个 4 个字符的字符串...
这看起来有点荒谬,我错过了一些明显的东西(PS 我已经使用 python 大约两周了)
这就是我想做的......
val = long(-5)
s = bytearray(pack("<i", val))
s.pop() # pop off msb
# write it out the way we want to then read it in the way the code does
fout = open("test.bat", "wb")
fout.write(s)
fout.close()
fin = open("test.bat", "rb")
inBytes = bytearray(fin.read(3))
# extend sign bit
if (inBytes[2] & 0x80):
inBytes.append(0xff)
else:
inBytes.append(0x00)
nb = inBytes.decode('ascii', 'replace')
# ERROR:root:after decode, len: 4 type: <type 'unicode'>
logging.error("after decode, len: {0} type: {1}".format(len(nb), type(nb)))
# struct.error: unpack requires a string argument of length 4
inInt32 = unpack('<i', inBytes.decode('ascii', 'replace'))[0]
fin.close()
您所需要的只是投射inBytes
回到str
:
>>> inint = struct.unpack('<i', str(inBytes))
>>> inint
(-5,)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)