本文主要记录java版的crc校验算法,顺带贴上c的crc校验函数
先上c的校验函数,本文java版的校验就是根据此函数而来的,希望能帮到大家
当时开发时通过一个在线检验工具辅助开发的。工具链接戳我
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
__STATIC_INLINE uint16_t CRC16Get8(const uint8_t* pu8Data, uint32_t u32Len) { uint32_t u32Index = 0; M0P_CRC->CR_f.CR = 0; M0P_CRC->RESULT = 0xABAB; for(u32Index = 0;u32Index<u32Len;u32Index++) { *((volatile uint8_t*)(&(M0P_CRC->DATA))) = pu8Data[u32Index]; }
return (M0P_CRC->RESULT_f.RESULT); }
|
java的校验,这是crc-16-8bit的校验,16bit、32bit的不适用,代码里面都有注释说明
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
|
public static byte[] getCrc16(byte[] arr_buff, int offset, int length){ int len = offset + length;
int crc = 0xABAB; int i, j; int data; for (i = offset; i < len; i++) { data = arr_buff[i]; crc = ((crc & 0xFF00) | (crc & 0x00FF) ^ (data & 0xFF)); for (j = 0; j < 8; j++) { if ((crc & 0x0001) > 0) { crc = crc >> 1; crc = crc ^ 0x8408; } else crc = crc >> 1; } } crc = crc ^ 0xFFFF; arr_buff[arr_buff.length - 2 ] = intToBytes(crc)[0]; arr_buff[arr_buff.length - 1 ] = intToBytes(crc)[1]; return arr_buff; }
|
intToBytes()转换方法函数
1 2 3 4 5 6 7 8 9 10
|
private static byte[] intToBytes(int value) { byte[] src = new byte[2]; src[1] = (byte) ((value>>8) & 0xFF); src[0] = (byte) (value & 0xFF); return src; }
|
为了明天更美好,每天进步一点点,加油!