Limit a hexadecimal number to 8-bits

I'm working on a serial interface. The serial packet includes the checksum. The checksum is limited to 8-bits (two-digit hexadecimal number). Any 8-bit math overflows are ignored.
For example, if the checksum is hexadecimal 1AF the serial packet only sends hexadecimal AF as the checksum.

I have written the code to get the checksum, but I have not been able to figure out how to limit the checksum to a two-digit hexadecimal number.

Here is the statement from the protocol document: The Checksum field is an unsigned 8-bit value that is calculated as the sum of the Length field, the Type field, and all the data bytes. During the summation of the fields, any 8-bit math overflows are ignored, i.e. the result is the sum modulo 256.

Use the Bitwise AND (&) operator

e.g...

const checksum = this + that + other
const checksumDecimal = checksum & 0xff // use checksumDecimal  if populating a buffer
const checksumHex = checksumDecimal .toString(16) // use checksumHex is appending to a string

e.g...

Perfect! Thank you!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.