0

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'\x60\x08\x46\x52\x41\x50\x5a\x45\x52\x31' #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'\x60\x08\x46\x52\x41\x50\x5a\x45\x52\x31\xb3' I get b'\x08FRAPZER1\xb3' it works, so I need to drop the 0xb3 and replace it with \xb3.

1 Answer 1

1

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])
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.