Compute Arithmetic Sum to Communicate with Machine Over Serial

人走茶凉 提交于 2019-12-24 19:45:24

问题


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:


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;



回答2:


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.



来源:https://stackoverflow.com/questions/2014391/compute-arithmetic-sum-to-communicate-with-machine-over-serial

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!