有时候 与硬件设备对接需要用到数据帧 为了保证数据帧在传输过程中的完整性 一般会在数据帧中加入异或校验值
示例
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;
    }