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;
    }
相关推荐
程序员张31 小时前
Maven编译和打包插件
java·spring boot·maven
ybq195133454312 小时前
Redis-主从复制-分布式系统
java·数据库·redis
weixin_472339462 小时前
高效处理大体积Excel文件的Java技术方案解析
java·开发语言·excel
小毛驴8503 小时前
Linux 后台启动java jar 程序 nohup java -jar
java·linux·jar
枯萎穿心攻击3 小时前
响应式编程入门教程第二节:构建 ObservableProperty<T> — 封装 ReactiveProperty 的高级用法
开发语言·unity·c#·游戏引擎
DKPT3 小时前
Java桥接模式实现方式与测试方法
java·笔记·学习·设计模式·桥接模式
Eiceblue4 小时前
【免费.NET方案】CSV到PDF与DataTable的快速转换
开发语言·pdf·c#·.net
好奇的菜鸟5 小时前
如何在IntelliJ IDEA中设置数据库连接全局共享
java·数据库·intellij-idea
m0_555762905 小时前
Matlab 频谱分析 (Spectral Analysis)
开发语言·matlab
DuelCode6 小时前
Windows VMWare Centos Docker部署Springboot 应用实现文件上传返回文件http链接
java·spring boot·mysql·nginx·docker·centos·mybatis