package com.handset.serialportlib;

public class CRCUtils {
    public static String genCrc(byte[] bytes) {
        int CRC = 0xffff;
        int POLYNOMIAL = 0xA001;

        for (byte b : bytes) {
            CRC ^= ((int) b & 0x00ff);
            for (int j = 0; j < 8; j++) {
                if ((CRC & 0x0001) != 0) {
                    CRC >>= 1;
                    CRC ^= POLYNOMIAL;
                } else {
                    CRC >>= 1;
                }
            }
        }

        int i = (CRC & 0x00ff) << 8 | (CRC & 0xff00) >> 8;
        String tmp = "00000000".concat(Integer.toHexString(i).toUpperCase());
        return tmp.substring(tmp.length() - 4);
    }

    public static String genCrc(String hexString) {
        byte[] bytes = ByteUtils.hexStrToBytes(hexString);
        int CRC = 0xffff;
        int POLYNOMIAL = 0xA001;

        for (byte b : bytes) {
            CRC ^= ((int) b & 0x00ff);
            for (int j = 0; j < 8; j++) {
                if ((CRC & 0x0001) != 0) {
                    CRC >>= 1;
                    CRC ^= POLYNOMIAL;
                } else {
                    CRC >>= 1;
                }
            }
        }

        int i = (CRC & 0x00ff) << 8 | (CRC & 0xff00) >> 8;
        String tmp = "00000000".concat(Integer.toHexString(i).toUpperCase());
        return tmp.substring(tmp.length() - 4);
    }

    public static void main(String[] args) {
        String tmp = "011314060E093620FF75C20060010100";
        String res = genCrc(tmp);
        int i = 0;
    }
}
