Skip to content
Advertisement

How to convert byte to hex?

I am needing to send some data over serial but before I send, I need to calculate the checksum using modulo 256. I can work out the checksum and display it as a hex value (in this case the checksum is 0xb3) but it displays it as 0xb3 but I need it to be xb3 as I am sending other messages before it.

I have tried encoding, bytes and bytearray, but can not get it to send the hexadecimal value. It sends '0xb3' as a string.

def calculate_csum(message):
    message = b'x60x08x46x52x41x50x5ax45x52x31' #just temp
    j = 0
    for i in message:
        j = j + i

    csum  = hex(j % 256)
    csum = csum.encode("ascii")
    print(csum)
    full_string = message + csum
    print (full_string)
    return csum

The output of the full string is b'x08FRAPZER10xb3' but if I hardcode it with b'x60x08x46x52x41x50x5ax45x52x31xb3' I get b'x08FRAPZER1xb3' it works, so I need to drop the 0xb3 and replace it with xb3.

Advertisement

Answer

No need to go through gyrations to convert csum to a string then back to a byte string, you want it as a single byte in the first place.

csum = bytes([j % 256])
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement