java异或校验

有时候 与硬件设备对接需要用到数据帧 为了保证数据帧在传输过程中的完整性 一般会在数据帧中加入异或校验值
示例

16进制数据帧

FE AB 01 10 00 10 00 01 02 03 04 05 06 00 00

转成string List

["FE","AB","01","10","00","10","00","01","02","03","04","05","06","00","00"]

异或校验

private String xor(List<String> dataFrame){
        Integer result = dataFrame.stream()
                .map(s -> Integer.parseInt(s,16))
                .reduce((t,k) -> t^k)
                .orElseThrow(RuntimeException::new);
        if(result < 16){
            return "0" + Integer.toHexString(result).toUpperCase();
        }else{
            return Integer.toHexString(result).toUpperCase();
        }
    }

得到方法返回值 53

按照协议 插入数据帧第5位 得到完整数据帧

FE AB 01 10 53 00 10 00 01 02 03 04 05 06 00 00

传输数据帧给硬件

ps:一般通过串口与硬件设备通信传输数据帧,是以字节数组的形式
所以上面的string List要转换为byte[]

	private byte[] toByteArray(List<String> dataFrame) {
        byte[] data = new byte[dataFrame.size()];

        for (int i = 0; i < dataFrame.size(); i++) {
            data[i] = (byte) Integer.parseInt(dataFrame.get(i), 16);
        }

        return data;
    }

收到硬件传输过来的数据帧一般也是byte[]的形式 可以转换为string List

	private List<String> toDataFrame(byte[] bytes) {
        List<String> dataFrame = Lists.newArrayList();
        for (byte b : bytes) {
            String hex = Integer.toHexString(0xFF & b);
            if (hex.length() == 1) {
                // 如果是一位的话,要补0
                hex = "0" + hex;
            }
            dataFrame.add(hex.toUpperCase());
        }
        return dataFrame;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值