Optimal Method to Verify Byte Checksums in Python

Feedback

Question:

As part of my work, I am sent various packets through the serial port. An example of such a packet is:

                         last 2 bytes
                              /
[ data length ] [ data ] [packet crc]

I encounter a crc issue with the value 125 (

sum(b'wx06') = 125


) in packet

b'wx06'


. The crc of the packet is calculated using

sum(data)

and the result obtained is

1655

. Even though I know that

1655

is equivalent to

b'w'

, I am uncertain about how to translate it to

125

and match it with the correct checksum. Is there a way to convert

1655

to the same value as
packet bytes
received, which is either

125

or

b'wx06'


? Do I need to use

binascii

or

struct

or something else to resolve this issue?

Thanks


Solution:

You can use

int.from_bytes

:

int.from_bytes(b'wx06', 'little')

or with

struct

:

struct.unpack("

Frequently Asked Questions