python长整型字节数_python pack 4字节整数,字节数组struct.pack中的字节

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("

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()

解决方案

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:

>>> import struct

>>> f = open('foo.bin', 'wb')

>>> f.write(struct.pack('

3

>>> f.close()

Python 2.x .. it's a str object.

>>> f = open('foo.bin', 'rb')

>>> raw = f.read()

>>> f.close()

>>> print "received", type(raw), repr(raw)

received '\xfb\xff\xff'

>>> if raw[2] >= '\x80':

... raw += '\xff'

... else:

... raw += '\x00'

...

>>> print "extended", type(raw), repr(raw)

extended '\xfb\xff\xff\xff'

>>> number = struct.unpack('

>>> print "number", number

number -5

>>>

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 b'\xfb\xff\xff'

>>> if raw[2] & 0x80:

... raw += b'\xff'

... else:

... raw += b'\x00'

...

>>> print("extended", type(raw), repr(raw))

extended b'\xfb\xff\xff\xff'

>>> number = struct.unpack('

>>> print("number", number)

number -5

>>>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值