Android与底层硬件通信,进行CRC16校验时,要考虑到无符号整形的原因,java会将超过的值变成负数
C算法:
Uint16 crc16 = 0;
Uint8 i = 0;
Uint16 Crc16Calc(Uint8 *data_arr, Uint8 data_len)
{
crc16 = 0;
for(i = 0; i < data_len; i++)
{
crc16 = (Uint16)(( crc16 >> 8) | (crc16 << 8));
crc16 ^= data_arr[i];
crc16 ^= (Uint16)(( crc16 & 0xFF) >> 4);
crc16 ^= (Uint16)(( crc16 << 8) << 4);
crc16 ^= (Uint16)((( crc16 & 0xFF) << 4) << 1);
}
Return crc16;
}
Java算法:
public static char Crc16Calc(byte[] data_arr, int data_len)
{
char crc16 = 0;
int i;
for(i =0; i < (data_len); i++)
{
crc16 = (char)(( crc16 >> 8) | (crc16 << 8));
crc16 ^= data_arr[i]& 0xFF;
crc16 ^= (char)(( crc16 & 0xFF) >> 4);
crc16 ^= (char)(( crc16 << 8) << 4);
crc16 ^= (char)((( crc16 & 0xFF) << 4) << 1);
}
return crc16;
}