Search code examples
micropythonraspberry-pi-pico

How to convert from bytearray/bytes?


I'm hashing with uhashlib in MicroPython on a Raspberry Pi Pico:

import sys
import os
import uhashlib
import time

time_now = "blergh"
hash_test = uhashlib.sha256(time_now).digest()

print(time_now)
print(hash_test)

This outputs:

blergh
b'Y|\x84W\xa1\x1d\x86cb~\x0bL\x1e\\\x92\xcd-\x93\x05\xddz\x0e\xe1\x9f\x9a\xc1H6\x93\xd8\x0c8'

which isn't useful. How to convert from bytes (b'...') in MicroPython?


Solution

  • Use ubinascii.hexlify and jump through hoops.

    ubinascii.hexlify() returns bytes. By decoding the bytes to a str and then converting that str to an int (with base16), we can then pass the value to hex(). There is no hex attribute for bytes in micropython.

    The below has been fully tested on the Raspberry Pi Pico running micropython 1.14. I suspect earlier versions would also work, as long as they possess both of the module dependencies.

    import ubinascii, uhashlib
    
    hs = uhashlib.sha256(b'blergh')
    
    def hexdigest(sha):
        return hex(int(ubinascii.hexlify(sha.digest()).decode(), 16))
    
    hx = hexdigest(hs) #0x597c8457a11d8663627e0b4c1e5c92cd2d9305dd7a0ee19f9ac1483693d80c38