计算算术和以通过串行与机器通信 [英] Compute Arithmetic Sum to Communicate with Machine Over Serial
问题描述
我正在通过串行方式与机器通信。协议通信规范的一部分指出,控制总和是从<'PS'>(包括),从<'data'>到<'CS'>的字节的算术总和
分组消息的结构如下:
<'PS'><'data'><'CS'>,其中:
<'PS'>-数据包大小
长度: 1
值:0x02至0x63
最大数据包长度为99个字节
<'data'>-数据
长度:1 ... 90字节
值:0x00-0xFF
数据部分的长度取决于命令。
<'CS'>-校验和
长度-1个字节
值:0x00-0xFF
示例:
ACK数据包:0x02 0x01 0x03 ,其中0x03是校验和。
那我该如何在C ++中计算这些字节的校验和?
看起来校验和是一个简单的和,取模256。
int sum = 0;
for(int j = 0; j< number_of_bytes_in_message; ++ j)
sum + = message [j];
总和%= 256; //,或者,如果您希望总和& = 255;
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++?
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;
这篇关于计算算术和以通过串行与机器通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!