tags:

views:

158

answers:

2

I am communicating with a machine over serial. Part of the protocol communication spec states that the control sum is an "arithmetic sum of bytes from <'PS'> (included), <'data'> to <'CS'>"

The packet messages are structured as follows:

<'PS'><'data'><'CS'>, where:

<'PS'> - Packet Size

Length: 1

Value: 0x02 to 0x63

Max packet length is 99 bytes

<'data'> - Data

Length: 1...90 bytes

Value: 0x00 - 0xFF

The length of the data part depends on the command.

<'CS'> - Check Sum

Length - 1 byte

Value: 0x00 - 0xFF

Example:

ACK Packet: 0x02 0x01 0x03 where 0x03 is the checksum.

So how do I compute the checksum for these bytes in C++?

+1  A: 

It looks like the checksum is a simple sum, modulo 256.

int sum = 0;
for (int j = 0;  j < number_of_bytes_in_message;  ++j)
   sum += message [j];

sum %= 256;  // or, if you prefer  sum &= 255;
wallyk
accepted but I ended up using `unsigned char cs = 0;` so if it is greater than 255, it resets to 0
0A0D
Don't forget to include the length in the checksum. sum = number_of_bytes_in_message.
Hans Passant
wallyk
@wallyk: gotcha.. It does not seem to work that way. Thanks for your help
0A0D
+1  A: 

Use an unsigned 8-bit type (uint8_t or unsigned char) as an accumulator, add each byte to it as you generate the packet, then send it as the checksum byte. Exactly how depends on how you intend to construct the packets.

Andrew McGregor
I am using char buff[256] and setting each byte to a hexadecimal value.
0A0D