我正试图使用struct.pack将python bytearray的内容打包成一个4字节有符号整数。不幸的是,pack想要一个字符串,所以在经过一些谷歌搜索之后,我想我需要把我的bytearray解码成一个字符串。我认为ascii的意思是因为ascii字符是一个字节长。不幸的是,ascii不想支持我的值>;127,所以我想使用replace。。。
但当我做这个解码返回一个unicode类型的对象,现在我的每个字节都是一个4个字符的字符串。。。
这看起来有点可笑,我遗漏了一些显而易见的东西(ps我已经使用python两周了)
这就是我要做的。。。val = long(-5)
s = bytearray(pack("
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:
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('
fin.close()