public static void main(String[] args) throws IOException {
byte[] bytes = new byte[] { 0x01, 0x03, 0x01, 0x48, 0x00, 0x0c };
System.out.println(getCRC(bytes));
}
public static String getCRC(String data) {
data = data.replace(" ", "");
int len = data.length();
if (!(len % 2 == 0)) {
return "0000";
}
int num = len / 2;
byte[] para = new byte[num];
for (int i = 0; i < num; i++) {
int value = Integer.valueOf(data.substring(i * 2, 2 * (i + 1)), 16);
para[i] = (byte) value;
}
return getCRC(para);
}
/**
* 计算CRC16校验码
*
* @param bytes 字节数组
* @return {@link String} 校验码
* @since 1.0
*/
public static String getCRC(byte[] bytes) {
int wCRCin = 0x0000; // initial value 65535
int wCPoly = 0x1021; // 0001 0000 0010 0001 (0, 5, 12)
for (byte b : bytes) {
for (int i = 0; i < 8; i++) {
boolean bit = ((b >> (7 - i) & 1) == 1);
boolean c15 = ((wCRCin >> 15 & 1) == 1);
wCRCin <<= 1;
if (c15 ^ bit)
wCRCin ^= wCPoly;
}
}
wCRCin &= 0xffff;
// 结果转换为16进制
String result = Integer.toHexString(wCRCin).toUpperCase();
if (result.length() != 4) {
StringBuffer sb = new StringBuffer("0000");
result = sb.replace(4 - result.length(), 4, result).toString();
}
//高位在前地位在后
// return result.substring(2, 4) + " " + result.substring(0, 2);
// 交换高低位,低位在前高位在后
//return result.substring(2, 4) + " " + result.substring(0, 2);
// return result.substring(0, 2) + " " + result.substring(2, 4) ;
return result;
}
}
Android CRC16 MODBUS校验算法
最新推荐文章于 2025-04-07 00:15:00 发布