Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

8-bit binary addition

Can someone explain how to calculate checksum with 8-bit binary addition? This is an excerpt from the documentation:

This is the general form of the messages:

STX | TYPE | FS | DATA | FS | CHK | ETX

STX is HEX 02

ETX is HEX 03

FS is HEX 15

The "type" is a unique, 1-byte message identifier (e.g., 'P' for Poll message). "Data" contains printable ASCII characters.

Checksum

The Checksum is computed on all characters, including all the <FS> characters, between <STX> and <CHK>. The Checksum is calculated by the 8-bit binary addition of all included characters with the 8th or parity bit assumed to be zero. Carries beyond the 8th bit are lost. The 8-bit result is converted into two printable ASCII Hex characters, ranging from 00 to FF, which are then inserted into the data stream as <CHK>. The Hex characters A-F are uppercase. The receiving device recalculates the checksum on the buffered message and compares it with the checksum it received. The comparison is the basis for subsequent acknowledgement (<ACK>) or negative acknowledgement (<NAK>) of the transmission.

like image 318
ekstrakt Avatar asked Mar 14 '26 15:03

ekstrakt


1 Answers

Treat each character as an integer value. Since each character's high bit is assumed to be zero (as in the spec doesn't say you need to check it), mask its value with something like this (pseudo-C/C++/Java/whatever):

get_next_character() & 0x7f;

Now you just do the add (pseudo-C/C++/Java/whatever):

int s = 0;
while(!end_of_string())
{
    s += get_next_character() & 0x7f;
    s &= 0xff;
}

This will consecutively add each ASCII character and remove everything past the 8th bit from the resulting sum. When you're all finished (C or badly-written C++):

printf("Checksum: %02x\n", s);  /* You may need %02X for uppercase.
                                   I don't remember my printf codes anymore. */

As an optimization (if you really need it -- unlikely in this case!) you can defer the s &= 0xff bit and instead use the truncation at the point of use for the checksum. This won't save you much on performance, however -- your I/O will be far more expensive -- and leads to the possibility of you forgetting to do it at some later date when you refactor your code.

like image 111
JUST MY correct OPINION Avatar answered Mar 16 '26 04:03

JUST MY correct OPINION



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!