Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert byte string in Micropython

Tags:

micropython

As noted here receiving a message through a Micropython socket results in being left with a byte string to work with. My question is how to convert this byte string to another usable format?

I have tried the likes of:

data = s.recv(64)
new = hex(data)

which results in errors such as:

TypeError: can't convert bytes to int

And: data = s.recv(64).hex() Resulting in:

AttributeError: 'bytes' object has no attribute 'hex'

I am fairly new to Python and Micro-python in general. As far as I can tell this has not been answered directly for Micropython.

If this has been answered specifically for Python3 I think it worthwhile to re-iterate it for Micropython since implementation can be slightly different and to perhaps find an acceptable 'best practice'.

like image 507
goldfishalpha Avatar asked Sep 02 '25 16:09

goldfishalpha


2 Answers

It's not clear exactly what you're trying to do.

The way you convert bytes into a string is by calling the .decode method. This gives you bytes:

data = s.recv(64)

And this transforms that into a string:

data = data.decode('utf-8')

But you're trying to call hex(), which takes a single integer and returns the corresponding hexadecimal value. That doesn't make much sense in the context of your question.

like image 194
larsks Avatar answered Sep 07 '25 14:09

larsks


I needed to convert a byte MAC address to a string representing hex values. @birdistheword99 showed me the way...

a MAC address retrieved from the system looks like: b'\xacg\xb27-\xcc'. This is not very reader friendly. To make it into a string of hex digits...

import binascii

mac_bytes = b'\xacg\xb27-\xcc'
mac_str = binascii.hexlify(mac_bytes).decode()
print(mac_str)

Yields...

ac67b2372dcc
like image 45
stanely Avatar answered Sep 07 '25 12:09

stanely