Python struct.unpack errors with TypeError: a byte

2019-08-09 11:04发布

问题:

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("<h",chr(b)+chr(a))[0]

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("<h",chr(b)+chr(a))[0]

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

Here is the link to the description of how the data is sent from the device RAW Wave Value (16-bit)

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.

回答1:

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

struct.unpack("<h", bytes([b, a]))[0]