python pack 4字节整数,带有字节数组struct.pack中的字节 [英] python pack 4 byte integer with bytes in bytearray struct.pack
问题描述
我正在尝试使用struct.pack将python字节数组的内容打包为4字节有符号整数.不幸的是,pack需要一个字符串,因此经过一番谷歌搜索之后,我想我需要将字节数组解码为一个字符串.我想出ascii的意思是因为ascii字符是一个字节长.不幸的是,ascii不想支持我的> 127的值,所以我认为我会使用replace ...
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...
但是当我这样做时,解码返回一个unicode类型的对象,现在我的每个字节都是4个字符串...
but when I do this decode returns an object of type unicode and now each of my bytes is a 4 character string...
这似乎有点荒谬,我缺少明显的东西(ps我已经使用python大约两周了)
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()
推荐答案
当您以二进制模式读取文件时,您将获得一个可以立即与struct.unpack
一起使用的对象.
When you read from a file in binary mode, you get an object that can be used immediately with struct.unpack
.
创建输入数据:
>>> import struct
>>> f = open('foo.bin', 'wb')
>>> f.write(struct.pack('<i', -5)[:3])
3
>>> f.close()
Python 2.x ..它是str
对象.
>>> f = open('foo.bin', 'rb')
>>> raw = f.read()
>>> f.close()
>>> print "received", type(raw), repr(raw)
received <type 'str'> '\xfb\xff\xff'
>>> if raw[2] >= '\x80':
... raw += '\xff'
... else:
... raw += '\x00'
...
>>> print "extended", type(raw), repr(raw)
extended <type 'str'> '\xfb\xff\xff\xff'
>>> number = struct.unpack('<i', raw)[0]
>>> print "number", number
number -5
>>>
Python 3.x ...这是一个bytes
对象.
Python 3.x ... it's a bytes
object.
>>> f = open('foo.bin', 'rb')
>>> raw = f.read()
>>> f.close()
>>> print("received", type(raw), repr(raw))
received <class 'bytes'> b'\xfb\xff\xff'
>>> if raw[2] & 0x80:
... raw += b'\xff'
... else:
... raw += b'\x00'
...
>>> print("extended", type(raw), repr(raw))
extended <class 'bytes'> b'\xfb\xff\xff\xff'
>>> number = struct.unpack('<i', raw)[0]
>>> print("number", number)
number -5
>>>
这篇关于python pack 4字节整数,带有字节数组struct.pack中的字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!