java异或校验

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

示例

16进制数据帧

bash 复制代码
FE AB 01 10 00 10 00 01 02 03 04 05 06 00 00

转成string List

bash 复制代码
["FE","AB","01","10","00","10","00","01","02","03","04","05","06","00","00"]

异或校验

java 复制代码
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位 得到完整数据帧

bash 复制代码
FE AB 01 10 53 00 10 00 01 02 03 04 05 06 00 00

传输数据帧给硬件

ps:一般通过串口与硬件设备通信传输数据帧,是以字节数组的形式

所以上面的string List要转换为byte[]

java 复制代码
	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

java 复制代码
	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;
    }
相关推荐
疯狂的喵5 小时前
C++编译期多态实现
开发语言·c++·算法
2301_765703145 小时前
C++中的协程编程
开发语言·c++·算法
m0_748708055 小时前
实时数据压缩库
开发语言·c++·算法
lly2024066 小时前
jQuery Mobile 表格
开发语言
惊讶的猫6 小时前
探究StringBuilder和StringBuffer的线程安全问题
java·开发语言
jmxwzy6 小时前
Spring全家桶
java·spring·rpc
Halo_tjn6 小时前
基于封装的专项 知识点
java·前端·python·算法
m0_748233177 小时前
30秒掌握C++核心精髓
开发语言·c++
Fleshy数模7 小时前
从数据获取到突破限制:Python爬虫进阶实战全攻略
java·开发语言
Duang007_7 小时前
【LeetCodeHot100 超详细Agent启发版本】字母异位词分组 (Group Anagrams)
开发语言·javascript·人工智能·python