You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

52 lines
1.5 KiB

package com.ccsens.util;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class CRCUtil {
public static void crc16(byte crc[], byte data[], int index, int len) {
for (int i = 0; i < len; i++) {
log.info("发送数据:{}",Integer.toHexString(data[i] & 0xFF));
}
// 预置16位crc寄存器,初值全部为1
int wcrc = 0xFFFF;
// 定义中间变量
int temp;
// 定义计数
int i = 0, j = 0, k = index;
// 循环计算每个数据
for (i = 0; i < len; i++)
{
// 将八位数据与crc寄存器亦或
temp = (data[k] & 0xFF);
// 指针地址增加,指向下个数据
k++;
// 将数据存入crc寄存器
wcrc ^= temp;
// 循环计算数据的
for (j = 0; j < 8; j++)
{
// 判断右移出的是不是1,如果是1则与多项式进行异或。
if ((wcrc & 0x0001) == 1)
{
// 先将数据右移一位
wcrc >>= 1;
// 与上面的多项式进行异或
wcrc ^= 0XA001;
} else// 如果不是1,则直接移出
{
// 直接移出
wcrc >>= 1;
}
}
}
// crc的值
temp = wcrc;
// crc的低八位
crc[0] = (byte)(wcrc & 0xFF);
// crc的高八位
crc[1] = (byte)((wcrc >> 8) & 0xFF);
}
}