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;
    }
相关推荐
小旋风-java6 分钟前
springboot整合dwr
java·spring boot·后端·dwr
Pandaconda11 分钟前
【计算机网络 - 基础问题】每日 3 题(二十六)
开发语言·经验分享·笔记·后端·计算机网络·面试·职场和发展
虽千万人 吾往矣11 分钟前
golang strings api接口
开发语言·后端·golang
JAVA坚守者11 分钟前
Maven常见解决方案
java·maven
景天科技苑14 分钟前
【Go语言】深入解读Go语言中的指针,助你拨开迷雾见月明
开发语言·后端·golang·指针·go指针·go语言指针
虽千万人 吾往矣14 分钟前
golang格式化输入输出
开发语言·后端·golang
MavenTalk16 分钟前
Python在进行LLM应用相关开发常用的技术框架
开发语言·python·大模型·llm·大语言模型
聊天宝快捷回复23 分钟前
必收藏,售后客服日常回复必备的话术 (精华版)
java·前端·数据库·经验分享·微信·职场发展·快捷回复
wanyuanshi24 分钟前
map的键排序方法
java·数据结构·算法
热爱前端的小wen27 分钟前
maven的介绍与安装
java·spring·maven·springboot