简体   繁体   中英

Python struct.unpack errors with TypeError: a bytes-like object is required, not '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("<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 Value 1 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("<h", bytes([b, a]))[0]

if you use python3 you can use the following lines for the received data and convert it to a short data type.

struct.unpack('<h', data)
struct.unpack('<h', data[0:4])
struct.unpack('<h', b''.join(…))

If it receives the data as a list, it uses converts the array to bytes:

struct.unpack('<h', bytes(data))

Remember you must convert your information to bytes and not send as str, in order to use unpack and decompress the information in the data type you require.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM