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;
    }
相关推荐
电子科技圈1 天前
SmartDV展示完整的边缘与连接IP解决方案,以高速和低功耗特性赋能移动、物联网和媒体处理设备创新
人工智能·嵌入式硬件·mcu·物联网·智能家居·智能硬件·iot
Dxy12393102161 天前
Python 使用正则表达式将多个空格替换为一个空格
开发语言·python·正则表达式
故事和你911 天前
洛谷-数据结构1-1-线性表1
开发语言·数据结构·c++·算法·leetcode·动态规划·图论
techdashen1 天前
Rust项目公开征测:Cargo 构建目录新布局方案
开发语言·后端·rust
一 乐1 天前
电影院|基于springboot + vue电影院购票管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·论文·毕设·电影院购票管理管理系统
星空椰1 天前
JavaScript 进阶基础:函数、作用域与常用技巧总结
开发语言·前端·javascript
恼书:-(空寄1 天前
JVM GC 日志分析 + 常见 GC 场景 + 实战参数调优
java·jvm
消失的旧时光-19431 天前
Spring Boot 实战(五):接口工程化升级(统一返回 + 异常处理 + 错误码体系 + 异常流转机制)
java·spring boot·后端·解耦
忒可君1 天前
C# winform 自制分页功能
android·开发语言·c#
Rust研习社1 天前
Rust 智能指针 Cell 与 RefCell 的内部可变性
开发语言·后端·rust