张世豪
15 小时以前 b272034a1fdbfe32b355fc6c264a4c45df107190
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package yaokong;
public class CRC16 {
    private static final int POLYNOMIAL = 0x1021;
    private static final int INITIAL_VALUE = 0xFFFF;
    
    // 计算给定数据段的CRC16校验值
    public static int calculateCRC16(byte[] data, int offset, int length) {
        int crc = INITIAL_VALUE;
        
        for (int i = offset; i < offset + length; i++) {
            crc ^= (data[i] & 0xFF) << 8;
            for (int j = 0; j < 8; j++) {
                if ((crc & 0x8000) != 0) {
                    crc = (crc << 1) ^ POLYNOMIAL;
                } else {
                    crc <<= 1;
                }
            }
        }
        
        return crc & 0xFFFF;
    }
}