problem with byte string decoding

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

problem with byte string decoding

Post by oli » Fri Oct 07, 2016 8:30 am

hi,
i have a byte string and need to transform it to an ascii string due to legacy code reasons.
here is the code:

Code: Select all

MicroPython v1.8.4 on 2016-09-09; PYBv1.1 with STM32F405RG
Type "help()" for more information.
>>> x = b'\xf7\x03\x14\x04\x00\x01'
>>> x.decode('ascii')
'\x07\x03\x14\x04\x00\x01'
If you look at the first character in 'x' it is \xf7. After the decoding it is only x07. Is this a bug or do i understand the decode() wrong!?

Thanks for help!
best regards,
Oli

oli
Posts: 17
Joined: Wed Aug 05, 2015 9:13 am

Re: problem with byte string decoding

Post by oli » Fri Oct 07, 2016 8:36 am

Ok.... iPython gave me the answer:

Code: Select all

UnicodeDecodeError: 'ascii' codec can't decode byte 0xf7 in position 0: ordinal not in range(128)
Then the behaviour is clear. So now the question is, how to get rid of the 'b' before the string?
I need the transform because of the following code:

Code: Select all

x = b'\xf7\x03\x14\x04\x00\x01'
''.join(x)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: join expects a list of str/bytes objects consistent with self object
where as:

Code: Select all

x = '\xf7\x03\x14\x04\x00\x01'
''.join(x)
'\xf7\x03\x14\x04\x00\x01'
succeeds!?!?

Any ideas?

User avatar
Roberthh
Posts: 3667
Joined: Sat May 09, 2015 4:13 pm
Location: Rhineland, Europe

Re: problem with byte string decoding

Post by Roberthh » Fri Oct 07, 2016 8:46 am

e.g.

Code: Select all

"".join([chr(c) for c in x])

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

Re: problem with byte string decoding

Post by deshipu » Fri Oct 07, 2016 8:55 am

Why are you calling join() on a single string in the first place?

oli
Posts: 17
Joined: Wed Aug 05, 2015 9:13 am

Re: problem with byte string decoding

Post by oli » Fri Oct 07, 2016 9:23 am

@Roberthh: Thanks!
@deshipu: Like i said - legacy code not written by me, so i want to get it running, without changing to much - if it finally runs, then i will see, whether this stuff is necessary ;)

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

Re: problem with byte string decoding

Post by pythoncoder » Sun Oct 09, 2016 10:04 am

@oli Nevertheless @deshipu is correct. Issuing join() with a single string as its argument achieves precisely nothing. I'd question the quality of the original code.
Peter Hinch
Index to my micropython libraries.

Post Reply