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;
    }
相关推荐
C雨后彩虹3 小时前
任务最优调度
java·数据结构·算法·华为·面试
heartbeat..3 小时前
Spring AOP 全面详解(通俗易懂 + 核心知识点 + 完整案例)
java·数据库·spring·aop
Jing_jing_X3 小时前
AI分析不同阶层思维 二:Spring 的事务在什么情况下会失效?
java·spring·架构·提升·薪资
SmartRadio5 小时前
CH585M+MK8000、DW1000 (UWB)+W25Q16的低功耗室内定位设计
c语言·开发语言·uwb
rfidunion5 小时前
QT5.7.0编译移植
开发语言·qt
rit84324995 小时前
MATLAB对组合巴克码抗干扰仿真的实现方案
开发语言·matlab
元Y亨H5 小时前
Nacos - 服务发现
java·微服务
微露清风5 小时前
系统性学习C++-第十八讲-封装红黑树实现myset与mymap
java·c++·学习
dasi02275 小时前
Java趣闻
java
大、男人5 小时前
python之asynccontextmanager学习
开发语言·python·学习