Java CRC16(modbus)校验计算

代码片段: 

public class CRCUtil {
    public static byte[] getCrc16(byte[] bytes, int length) {
        if (bytes.length < length) return new byte[]{0, 0};
        int CRC = 0x0000ffff;
        int POLYNOMIAL = 0x0000a001;
        int i, j;
        for (i = 0; i < 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 new byte[]{(byte) (CRC & 0x00ff), (byte) (CRC >> 8)};
    }

    public static boolean validCrc16(byte[] bytes) {
        byte[] crc16 = getCrc16(bytes, bytes.length - 2);
        return crc16[0] == bytes[bytes.length - 2] && crc16[1] == bytes[bytes.length - 1];
    }


}



    public byte[] getCommand() throws Exception {

        byte[] result = new byte[8];
        result[0] = this.addressIndex.byteValue();
        result[1] = (byte) this.commandType;
        result[2] = ByteUtils.getHighByte(this.registerNumber);
        result[3] = ByteUtils.getLowByte(this.registerNumber);
        result[4] = ByteUtils.getHighByte(this.length);
        result[5] = ByteUtils.getLowByte(this.length);
        result[6] = CRCUtil.getCrc16(result, 6)[0];
        result[7] = CRCUtil.getCrc16(result, 6)[1];

        return result;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值