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'.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With