代码可用于CRC     16校验,十六进制、二进制、十进制转换,十六进制与字节数组转换,字符串补0,在对接物联网设备或其它需要校验的前端设备经常会用到,在这里做一下分享。


import java.io.IOException;

public class Crc16modules {
    public static String getCRC(String data) {
        data = data.replace(" ", "");
        int len = data.length();
        if (!(len % 2 == 0)) {
            return "0000";
        }
        int num = len / 2;
        byte[] para = new byte[num];
        for (int i = 0; i < num; i++) {
            int value = Integer.valueOf(data.substring(i * 2, 2 * (i + 1)), 16);
            para[i] = (byte) value;
        }
        return getCRC(para);
    }

    /**
     * 计算CRC16校验码
     *
     * @param bytes 字节数组
     * @return {@link String} 校验码
     * @since 1.0
     */
    public static String getCRC(byte[] bytes) {
        // CRC寄存器全为1
        int CRC = 0x0000ffff;
        // 多项式校验值
        int POLYNOMIAL = 0x0000a001;
        int i, j;
        for (i = 0; i < bytes.length; i++) {
            CRC ^= ((int) bytes[i] & 0x000000ff);
            for (j = 0; j < 8; j++) {
                if ((CRC & 0x00000001) != 0) {
                    CRC >>= 1;
                    CRC ^= POLYNOMIAL;
                } else {
                    CRC >>= 1;
                }
            }
        }
        // 结果转换为16进制
        String result = Integer.toHexString(CRC).toUpperCase();
        if (result.length() != 4) {
            StringBuffer sb = new StringBuffer("0000");
            result = sb.replace(4 - result.length(), 4, result).toString();
        }
        //高位在前地位在后
        //return result.substring(2, 4) + " " + result.substring(0, 2);
        // 交换高低位,低位在前高位在后
        return result.substring(2, 4) + " " + result.substring(0, 2);
    }

    /**
     * 十六进制数据转换为十进制字符串数
     *
     * @param hex
     * @return
     */
    public static String hexToDec(String hex) {
        int data = Integer.parseInt(hex, 16);
        return Integer.toString(data, 10);
    }

    /**
     * 十六进制数据转换为二进制字符串数
     *
     * @param hex
     * @return
     */
    public static String hexToBinary(String hex) {
        int i = Integer.parseInt(hex, 16);
        String bin = Integer.toBinaryString(i);
        String str = addZeroForStr(bin,10,1);
        return new StringBuffer(str).reverse().toString();
    }

    /**
     * 给字符串的左补0或右补0
     * @param str  要处理的字符串
     * @param length 补0后字符串总长度
     * @param type  1-左补0  2-右补0
     * @return
     */
    public static String addZeroForStr(String str, int length,int type) {
        int strLen = str.length();
        if (strLen < length) {
            while (strLen < length) {
                StringBuffer sb = new StringBuffer();
                if (type == 1) {
                    // 左补0
                    sb.append("0").append(str);
                } else if (type == 2) {
                    //右补0
                    sb.append(str).append("0");
                }
                str = sb.toString();
                strLen = str.length();
            }
        }
        return str;
    }

    /**
     * 将十六进制的字符串转换成字节数组
     *
     * @param hexString
     * @return
     */
    public static byte[] hexStrToBinaryStr(String hexString) {


        if (hexString == null||"".equals(hexString)) {
            return null;
        }

        hexString = hexString.replaceAll(" ", "");

        int len = hexString.length();
        int index = 0;


        byte[] bytes = new byte[len / 2];

        while (index < len) {

            String sub = hexString.substring(index, index + 2);

            bytes[index / 2] = (byte) Integer.parseInt(sub, 16);

            index += 2;
        }


        return bytes;
    }

    //字节数组转换为十六进制
    public static String bytesToHexString(byte[] src) {
        StringBuffer sb = new StringBuffer("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v).toUpperCase();
            if (hv.length() < 2) {
                sb.append(0);
            }
            sb.append(hv);
            if (i != src.length - 1) {
                sb.append(" ");
            }
        }
        return sb.toString();

    }

    //带符号十六进制转换十进制
    public static int signHextoInt(String strHex){
        int ia  = Integer.parseInt(strHex,16);
        //不带符号十六进制转换十进制
        //System.out.println("ia:  "+ia);
        String is=  String.valueOf((Integer.valueOf(strHex, 16).shortValue()));
        return Integer.parseInt(is);
    }

    public static void main(String[] args) throws IOException {
        //01 03 02 01 54 B8 2B
        String frame = "01 04 00 31 00 08";
        System.out.println(getCRC(frame));

    }

}

更多推荐