Conmi的正确答案——java计算Modbus CRC16

1、获取CRC的整数

    /**
     * 计算CRC16校验码(获取CRC的整数)
     *
     * @param bytes 被校验的字节数组
     * @return 返回CRC16校验码
     */
    public static int getCrcIntValue(Byte[] bytes) {
        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;
                }
            }
        }

        return crc;
    }

2、获取CRC的字节数组

    /**
     * 计算CRC16校验码(获取CRC的字节)
     *
     * @param bytes 被校验的字节数组
     * @return 返回CRC16校验码
     */
    public static Byte[] getCrcBytes(Byte[] bytes) {
        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;
                }
            }
        }

        List<Byte> crcBytes = new ArrayList<>();

        // MODBUS的低位在前
        crcBytes.add((byte) (crc & 0xff));
        crcBytes.add((byte) (crc >> 8));

        return crcBytes.toArray(new Byte[0]);
    }

3、获取CRC的字符串


    /**
     * 计算CRC16校验码(获取CRC的字符串)
     *
     * @param bytes 被校验的字节数组
     * @return 返回CRC16校验码
     */
    public static String getCrcString(Byte[] bytes) {
        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;
                }
            }
        }

        return String.format("%02X", (byte) (crc & 0xff)) + String.format("%02X", (byte) (crc >> 8));
    }

你可能感兴趣的:(java,开发语言)