struct issue

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
oli
Posts: 17
Joined: Wed Aug 05, 2015 9:13 am

struct issue

Post by oli » Tue Oct 11, 2016 11:12 am

Hi,

i have a strange issue:

Code: Select all

>>> struct.unpack('>B', '\x7f')[0]
127
>>> struct.unpack('>B', '\x80')[0]
194
As fa as the documentation from python / struct says, "B" is an unsigned int, and so it should give the correct value of 128 - or am i wrong?

thanks!
Oli

User avatar
pythoncoder
Posts: 5956
Joined: Fri Jul 18, 2014 8:01 am
Location: UK
Contact:

Re: struct issue

Post by pythoncoder » Tue Oct 11, 2016 11:16 am

The buffer argument should be a bytes object thus:

Code: Select all

>>> import ustruct as struct
>>> struct.unpack('>B', b'\x80')[0]
128
>>> 
Peter Hinch
Index to my micropython libraries.

User avatar
deshipu
Posts: 1388
Joined: Thu May 28, 2015 5:54 pm

Re: struct issue

Post by deshipu » Tue Oct 11, 2016 11:52 am

The value `"\x80"` is somewhat unfortunate, as it has special meaning in utf8, which is used by default in non-byte strings.

User avatar
pythoncoder
Posts: 5956
Joined: Fri Jul 18, 2014 8:01 am
Location: UK
Contact:

Re: struct issue

Post by pythoncoder » Wed Oct 12, 2016 6:24 am

Passing a string as the second arg is invalid. Alas MicroPython fails silently; Cpython provides an explanatory error message:

Code: Select all

>>> import struct
>>> struct.unpack('>B', '\x7f')[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' does not support the buffer interface
>>> 
With a bytes or bytearray instance, all possible 8-bit values are acceptable.
Peter Hinch
Index to my micropython libraries.

Post Reply