python pack 4字节整数,字节数组位于bytearray struct.pack中
我正在尝试使用 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()
I am attempting to pack the contents of a python bytearray into a 4byte signed integer using struct.pack. Unfortunately, pack wants a string, so after some googling I figured I needed to decode my bytearray to a string. I figured ascii meant since because an ascii character is a byte long. Unfortunately, ascii did not want to support my values > 127, so I thought I would use replace...
but when I do this decode returns an object of type unicode and now each of my bytes is a 4 character string...
This just seems a little ridiculous, im missing something obvious (ps I have been using python for about two weeks)
here is what I am trying to do...
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()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您所需要做的就是将
inBytes
转换回str
:All you need is to cast
inBytes
back tostr
:当您以二进制模式读取文件时,您将获得一个可以立即与 struct.unpack 一起使用的对象。
创建输入数据:
Python 2.x ..它是一个
str
对象。Python 3.x ...它是一个
bytes
对象。When you read from a file in binary mode, you get an object that can be used immediately with
struct.unpack
.Creating the input data:
Python 2.x .. it's a
str
object.Python 3.x ... it's a
bytes
object.