1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
| import java.util.Arrays;
public class CRC16Modbus { private static final int[] CRC_TABLE = new int[256];
static { for (int i = 0; i < 256; i++) { int crc = i; for (int j = 8; j > 0; j--) { if ((crc & 1) != 0) { crc = (crc >>> 1) ^ 0xA001; } else { crc >>>= 1; } } CRC_TABLE[i] = crc; } }
public static byte[] calculateCRC(byte[] data) { int crc = 0xFFFF;
for (byte b : data) { crc = (crc >>> 8) ^ CRC_TABLE[(crc ^ b) & 0xFF]; }
byte crcLow = (byte) (crc & 0xFF); byte crcHigh = (byte) ((crc >>> 8) & 0xFF);
return new byte[]{crcLow, crcHigh}; }
public static void main(String[] args) { byte[] data = {0x01, 0x03, 0x00, 0x65, 0x00, 0x05}; byte[] crc = calculateCRC(data); String hexString = ByteArrayToHexString(data); String format = String.format("%02X%02X%n", crc[0], crc[1]); System.out.println(hexString + format);
byte[] data3 = {0x01, 0x03, 0x00, 0x65, 0x00, 0x03, 0x15, (byte) 0xD4}; }
public static String ByteArrayToHexString(byte[] data) { StringBuilder hexString = new StringBuilder(); for (byte b : data) { hexString.append(String.format("%02X", b)); } return hexString.toString(); }
private static void parseResponse(byte[] response) { if (response.length < 5) { System.out.println("响应数据无效"); return; }
byte deviceAddress = response[0]; byte functionCode = response[1]; byte dataLength = response[2]; byte[] data = Arrays.copyOfRange(response, 3, 3 + dataLength); byte[] crc = Arrays.copyOfRange(response, 3 + dataLength, 3 + dataLength + 2);
System.out.println("设备地址: " + String.format("%02X", deviceAddress)); System.out.println("功能码: " + String.format("%02X", functionCode)); System.out.println("数据长度: " + String.format("%02X", dataLength)); System.out.println("数据: " + byteArrayToHexString(data)); System.out.println("CRC校验和: " + byteArrayToHexString(crc)); }
private static byte[] hexStringToByteArray(String s) { int len = s.length(); byte[] data = new byte[len / 2]; for (int i = 0; i < len; i += 2) { data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i + 1), 16)); } return data; }
private static String byteArrayToHexString(byte[] bytes) { StringBuilder sb = new StringBuilder(); for (byte b : bytes) { sb.append(String.format("%02X", b)); } return sb.toString(); } }
|