#
whycq
2024-08-15 e54492fb532366faac8aa5d46ad8905ea3ff38d5
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
38
39
40
41
package com.example.agvcontroller.protocol;
 
/**
 * CRC16循环冗余校验码
 * Created by vincent on 2023/3/13
 */
public class CRCUtils {
 
    /**
     * 一个字节占 8位
     */
    private static final int BITS_OF_BYTE = 8;
 
    /**
     * 多项式
     */
    private static final int POLYNOMIAL = 0XA001;
 
    /**
     * CRC寄存器默认初始值
     */
    private static final int INITIAL_VALUE = 0XFFFF;
 
    /**
     * CRC16 编码
     * @param bytes 编码内容
     * @return 编码结果
     */
    public static int crc16(byte[] bytes) {
        int res = INITIAL_VALUE;
        for (byte data : bytes) {
            // 把byte转换成int后再计算
            res = res ^ (data & 0XFF);
            for (int i = 0; i < BITS_OF_BYTE; i++) {
                res = (res & 0X0001) == 1 ? (res >> 1) ^ POLYNOMIAL : res >> 1;
            }
        }
        return res;
    }
 
}