| | |
| | | package com.ard.utils.tcp; |
| | | |
| | | import com.ard.utils.ByteUtils; |
| | | |
| | | import javax.xml.bind.DatatypeConverter; |
| | | import java.util.ArrayList; |
| | | import java.util.Arrays; |
| | |
| | | } |
| | | |
| | | /** |
| | | * crc32校验检查 |
| | | * 刘苏义 |
| | | * 2023/7/4 11:24 |
| | | */ |
| | | public static Boolean CRC32Check(byte[] packet) { |
| | | //System.out.println(DatatypeConverter.printHexBinary(packet)); |
| | | int headerLength = 3;//包头3个字节 |
| | | int footerLength = 3;//包尾3个字节 |
| | | int crcLength = 4;//crc校验4个字节 |
| | | //去掉包头包尾 |
| | | byte[] payloadCrc32 = ByteUtils.removeHeaderAndFooter(packet, headerLength, footerLength); |
| | | //System.out.println(DatatypeConverter.printHexBinary(payloadCrc32)); |
| | | //获取到数据携带的crc32值 |
| | | byte[] oldCrc32 = ByteUtils.getLastBytes(payloadCrc32, crcLength); |
| | | //去掉包头包尾crc32字节,仅保留负载 |
| | | byte[] payload = ByteUtils.removeHeaderFooterAndCRC(packet, headerLength, footerLength, crcLength); |
| | | // System.out.println(DatatypeConverter.printHexBinary(payload)); |
| | | //计算负载的crc32值 |
| | | byte[] NewCrc32 = ByteUtils.parseCrc32(payload); |
| | | System.out.println("old:"+DatatypeConverter.printHexBinary(oldCrc32)); |
| | | System.out.println("new:"+DatatypeConverter.printHexBinary(NewCrc32)); |
| | | //判断数据的crc32校验值和计算值是否相同 |
| | | if (Arrays.equals(oldCrc32, NewCrc32)) { |
| | | return true; |
| | | } else { |
| | | return false; |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 获取包结束索引 |
| | | */ |
| | | public static int findPacketEndIndex(List<Byte> buffer, byte[] packetEnd) { |
| | |
| | | * 去掉包头和包尾校验及转义 |
| | | */ |
| | | public static byte[] transferData(byte[] data) { |
| | | data = Arrays.copyOfRange(data, 3, data.length); |
| | | data = Arrays.copyOfRange(data, 0, data.length - 7); |
| | | int headerLength = 3;//包头3个字节 |
| | | int footerLength = 3;//包尾3个字节 |
| | | int crcLength = 4;//crc校验4个字节 |
| | | data= ByteUtils.removeHeaderFooterAndCRC(data,headerLength,footerLength,crcLength); |
| | | String dataStr = DatatypeConverter.printHexBinary(data); |
| | | if (dataStr.contains("01020201")) {//转义01020201 |
| | | dataStr = dataStr.replaceAll("01020201", "010201"); |