我確實測驗了我在網上找到的 crc-16/ibm 實作。當我用十六進制位元組陣列測驗它時,它作業正常,但如果我包含一些0x00值,則它不會給出正確的結果。這是它的代碼
unsigned short ComputeCRC16(const unsigned char* buf, unsigned int len) {
unsigned short crc = 0;
for (unsigned int j = 0; j < len; j )
{
unsigned char b = buf[j];
for (unsigned char i = 0; i < 8; i )
{
crc = ((b ^ (unsigned char)crc) & 1) ? ((crc >> 1) ^ 0xA001) : (crc >> 1);
b >>= 1;
}
}
return crc;
}
我用以下代碼對其進行了測驗:
int main() {
//fe b5 5f f7
unsigned char buf1[4096] = { 0xfe, 0xb5, 0x5f, 0xf7 };
//fe b5 00 5f f7 00
unsigned char buf2[4096] = { 0xfe, 0xb5, 0x00, 0x5f, 0xf7, 0x00 };
int a = strlen(buf1);
unsigned short res = ComputeCRC16(buf1, a);
printf("res = x\n", res); //res : 7858, the result is correct
int b = strlen(buf2);
unsigned short res = ComputeCRC16(buf2, b);
printf("res = x\n", res); //res : d781, the result is not correct
return 0; //the correct result : 26EE
}
驗證結果我使用這個網站:https : //www.lammertbies.nl/comm/info/crc-calculation
uj5u.com熱心網友回復:
您的 CRC 例程給出了正確的結果。是你的測驗錯了。strlen(p)回傳第一個零位元組之前的位元組數p。對于buf2,那是四個,而不是您想要的五個。因為buf1它甚至沒有定義,因為在該陣列之后記憶體中可以有任何東西。如果編譯器碰巧在陣列后面放了零,您可能會得到四個。
對于測驗,您應該簡單地len手動提供。(buf1, 4), (buf2, 5).
順便說一句,該代碼可能會更有效率。不必b每次都測驗。與bto start 的異或運算具有相同的效果:
crc ^= buf[j];
for (unsigned char i = 0; i < 8; i )
crc = crc & 1 ? (crc >> 1) ^ 0xa001 : crc >> 1;
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/380473.html
