Search code examples
micropython

Convert byte string in 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'.


Solution

  • 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.