java/android modbus RTU CRC16验证跟C和.net完全一样

public static String getCrcCheckStr(String inStr) {

        int[] inHex = new int[inStr.length() / 2];
        for (int i = 0; i < inHex.length; i++) {
            inHex[i] = Integer.parseInt(inStr.substring(i * 2, i * 2 + 2), 16);
        }

        String checks = addZero(Integer.toBinaryString(CRC_Check(inHex)), 16);
        String srt_H = Integer.toHexString(Integer.valueOf(checks.substring(0, 8), 2));//取高八位
        String crc_L = Integer.toHexString(Integer.valueOf(checks.substring(checks.length() - 8, checks.length()), 2));//取低八位

        srt_H = srt_H.length() < 2 ? "0" + srt_H : srt_H;
        crc_L = crc_L.length() < 2 ? "0" + crc_L : crc_L;

        return crc_L + srt_H;
    }

    /**
     * 将元数据前补零,补后的总长度为指定的长度,以字符串的形式返回
     */
    public static String addZero(String sourceDate, int formatLength) {
        int originalLen = sourceDate.length();
        if (originalLen < formatLength) {
            for (int i = 0; i < formatLength - originalLen; i++) {
                sourceDate = "0" + sourceDate;
            }
        }
        return sourceDate;
    }

    /**
     * 通过CRC算法获取校验和
     *
     * @param buf 需要校验的数据
     * @return 16进制的校验和
     */
    public static int CRC_Check(int [] buf) {
        int returnValue = 0XFFFF;
        for (int i = 0; i < buf.length; i++) {
            returnValue ^= buf[i];
            for (int j = 0; j < 8; j++) {
                if ((returnValue & 0X01) != 0) {
                    returnValue = (returnValue >> 1) ^ 0XA001;
                } else {
                    returnValue = returnValue >> 1;
                }
            }
        }
        return returnValue;
    }

 

你可能感兴趣的:(modbus,crc,crc16,java,modbus,16)