/**
* crc16 X16+x15+x2+1
* 16进制报文是 02 03 00 00 00 40 CRC16
* 传输的str:“020300000040”
* 结果:4409
* @param str
* @return
*/
public static String getCRC(String str) {
byte[] bytes = ByteUtil.hexStr2bytes(str);
int CRC = 0x0000ffff;
int POLYNOMIAL = 0x0000a001;
int i, j;
for (i = 0; i < bytes.length; i++) {
CRC ^= ((int) bytes[i] & 0x000000ff);
for (j = 0; j < 8; j++) {
if ((CRC & 0x00000001) != 0) {
CRC >>= 1;
CRC ^= POLYNOMIAL;
} else {
CRC >>= 1;
}
}
}
String crc = Integer.toHexString(CRC);
if (crc.length() == 2) {
crc = "00" + crc;
} else if (crc.length() == 3) {
crc = "0" + crc;
}
crc = crc.substring(2, 4) + crc.substring(0, 2);
return crc.toUpperCase();
}
CRC校验 java modbus
最新推荐文章于 2024-05-20 13:32:10 发布