代码片段:
public class CRCUtil {
public static byte[] getCrc16(byte[] bytes, int length) {
if (bytes.length < length) return new byte[]{0, 0};
int CRC = 0x0000ffff;
int POLYNOMIAL = 0x0000a001;
int i, j;
for (i = 0; i < length; i++) {
CRC ^= ((int) bytes[i] & 0x000000ff);
for (j = 0; j < 8; j++) {
if ((CRC & 0x00000001) != 0) {
CRC >>= 1;
CRC ^= POLYNOMIAL;
} else {
CRC >>= 1;
}
}
}
return new byte[]{(byte) (CRC & 0x00ff), (byte) (CRC >> 8)};
}
public static boolean validCrc16(byte[] bytes) {
byte[] crc16 = getCrc16(bytes, bytes.length - 2);
return crc16[0] == bytes[bytes.length - 2] && crc16[1] == bytes[bytes.length - 1];
}
}
public byte[] getCommand() throws Exception {
byte[] result = new byte[8];
result[0] = this.addressIndex.byteValue();
result[1] = (byte) this.commandType;
result[2] = ByteUtils.getHighByte(this.registerNumber);
result[3] = ByteUtils.getLowByte(this.registerNumber);
result[4] = ByteUtils.getHighByte(this.length);
result[5] = ByteUtils.getLowByte(this.length);
result[6] = CRCUtil.getCrc16(result, 6)[0];
result[7] = CRCUtil.getCrc16(result, 6)[1];
return result;
}