串口通信检验和

2023-08-24 14:38:05 浏览数 (1)

校验和: 发送方的检验和位 byte为 _sum = 2^n - (sum(data) & 2 ^n-1) 接收方检测: ((sum(data) _sum) & (2^n-1)) 如果为0则检验正确

n代表:发送数据的位数

代码语言:javascript复制
 byte[] buf = new byte[12];
            buf[0] = 0XEB;
            buf[1] = 0x91;
            buf[2] = 0x00;
            buf[3] = 0x01;
            buf[4] = 0x10;


            buf[5] = 0x00;
            buf[6] = 0x00;
            buf[7] = 0x00;
            buf[8] = 0x00;
            buf[9] = 0x00;
            buf[10] = 0x00;

            buf[11] = 0x00;

            // _sum = 2 ^ n - (sum(data) & (2 ^ n - 1))

            byte sum = 0x00;
            for (int i = 0; i <= 10; i  )
            {
                sum  = buf[i];
            }

            buf[11] = (byte)(0x100 - (sum & 0xFF));


            byte receive = (byte)((sum   buf[11]) & (0xff));

receive为0 代表下位机收到的正常

0 人点赞