python byte struct_python pack 4字节整数,字节在bytearray struct.p中

我正试图使用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()

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值