python3 struct unpack_带有TypeError的Python struct.unpack错误:需要一个类似字节的对象,而不是'str'...

Can someone please help with the following line of code and Error? I am unfamiliar with python value conversions.

The specific line that generates the error is:

value = struct.unpack("

TypeError: a bytes-like object is required, not 'str'

The code fragment is:

if packet_code ==0x80: # raw value

row_length = yield

a = yield

b = yield

value = struct.unpack("

The input data is:

b'\x04\x80\x02\x00\xb2\xcb\xaa\xaa\x04\x80\x02\x00p\r\xaa\xaa\x04\x80\x02\x00]

\xaa\xaa\x04\x80\x02\x00@=\xaa\xaa\x04\x80\x02\x007F\xaa\xaa\x04\x80\x02\x00\!\xaa\xaa\x04\x80\x02\x00=@\xaa\xaa\x04\x80\x02\x00=@\xaa\xaa\x04\x80\x02\x00i\x14\xaa\xaa\x04\x80\x02\x00]

\xaa\xaa\x04\x80\x02\x00p\r\xaa\xaa\x04\x80\x02\x00\x80\xfd\xaa\xaa

I am using python 3.5. This code seems to work in the older versions.

Here is the link to similar parser code where it may have worked with previous versions of Python:

Parser Code Link

This Data Value consists of two bytes, and represents a single raw wave sample. Its value is a signed 16-bit integer that ranges from -32768 to 32767. The first byte of the Value represents the high-order bits of the twos-compliment value, while the second byte represents the low-order bits. To reconstruct the full raw wave value, simply shift the first byte left by 8 bits, and bitwise-or with the second byte:

short raw = (Value[0]<<8) | Value[2];

where Value[0] is the high-order byte, and Value1 is the low-order byte.

In systems or languages where bit operations are inconvenient, the following arithmetic operations may be substituted instead:

raw = Value[0]*256 + Value[1];

if( raw >= 32768 ) raw = raw - 65536;

Really appreciate any help as I am currently stuck.

解决方案

When you are using Python 2.x str is a byte array. For Python 3, you must use bytes like this:

struct.unpack("

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值