czt
2024-07-13 1c1472f51d68382f913e413aa827fd0b028ab589
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
42
43
44
45
46
47
48
49
50
51
52
package com.ld.igds.protocol.bhzn.utils;
 
public class CRC {
    
    /*寄存器初始值*/
    private final int regInitValue;
    private int register;
    /*CRC 多项式 modbus 多项式0x8005*/ 
    private final int polynomial;
    
    public CRC() {
        this(0xffff, 0x8005);
    }
    
    public CRC(int register, int polynomial) {
        this.register = register;
        this.regInitValue = register;
        this.polynomial = Integer.reverse(polynomial)>>>Integer.numberOfLeadingZeros(polynomial);
    }
 
    private void byteCRC(byte byt) {
        register ^= (byt&0xff);
        for(int i=0; i<8; i++){
            if((register&1)==0){
                register >>= 1;
            }else{
                register = (register >> 1)^polynomial;
            }
        }
    }
    
    public synchronized int crc(byte[] byts) {
        if(null==byts||byts.length==0){
            return 0;
        }
        for(int i=0; i<byts.length; i++){
            byteCRC(byts[i]);
        }
        int retn = register;
        register = this.regInitValue;
        return retn;
    }
    
    public static void main(String[] args){
        CRC crc = new CRC();
        byte[] data = {(byte)0x81, 0x12, 0x17, (byte)0xfe};
        System.out.println(Integer.toHexString(crc.crc(data)));
        data = new byte[]{2, 7};
        System.out.println(Integer.toHexString(crc.crc(data)));
    }
    
}