LRC校驗
縱向冗餘校驗(Longitudinal Redundancy Check,簡稱:LRC)是通信中常用的一種校驗形式,也稱LRC校驗或縱向校驗。它是一種從縱向通道上的特定比特串產生校驗比特的錯誤檢測方法。在行列格式中(如磁帶),LRC經常是與VRC一起使用,這樣就會爲每個字符校驗碼。在工業領域Modbus協議Ascii模式採用該算法。
具體算法如下:
1、對需要校驗的數據(2n個字符)兩兩組成一個16進制的數值求和。
2、將求和結果與256求模。
3、用256減去所得模值得到校驗結果(另一種方法:將模值按位取反然後加1)。
例如16進制數據:01 A0 7C FF 02
(16進制計算) 求和:01 + A0 + 7C + FF + 02 = 21E 取模:21E % 100 = 1E 計算:100 - 1E = E2
(10進制計算) 求和:01 + 160 + 124 + 255 + 02 = 542 取模:542 % 256 = 30 計算:256 - 30 = 226
————————————————
版權聲明:本文爲CSDN博主「youandme520」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/youandme520/article/details/107008121
在線驗證工具
http://www.ip33.com/lrc.html
golang 實現 thank for github
https://github.com/TheCount/go-lrc
c語言實現
// method 1
unsigned char calc_lrc2(unsigned char* data, int data_len)
{
unsigned char lrc = 0;
for (int i = 0; i < data_len; i++)
{
lrc ^= data[i];
printf("%02X\n",lrc);
}
return lrc;
}
// method 2
int xor16(unsigned char buf[], int index, long bytetotal)
{
int buff=0;
int i;
for (i = index; i <bytetotal; i++) {
buff = buff^(int)buf[i];
}
return buff;
}