【发布时间】:2014-09-01 21:37:24
【问题描述】:
在 Java 中使用多项式 x^16 + x^12 + x^5 + 1 (0x1081) 计算 CCITT 标准 CRC 时需要帮助。我在互联网上尝试了很多示例,但每个示例都返回与示例中的值不同的值。
例如对于这个数组 [0xFC] [05] [11],结果需要是 [27] [56]。
使用此代码:
public static void main(String[] args) {
byte[] array = new byte[3];
array[0] = (byte) 0xFC;
array[1] = (byte) 0x05;
array[2] = (byte) 0x11;
// array[3] = (byte) 0x00;
// array[4] = (byte) 0x00;
System.out.println(Integer.toHexString(crc16(array)));
}
private static final int POLYNOMIAL = 0x1081;
private static final int PRESET_VALUE = 0xFFFF;
public static int crc16(byte[] data) {
int current_crc_value = PRESET_VALUE;
for (int i = 0; i < data.length; i++) {
current_crc_value ^= data[i] & 0xFF;
for (int j = 0; j < 8; j++) {
if ((current_crc_value & 1) != 0) {
current_crc_value = (current_crc_value >>> 1) ^ POLYNOMIAL;
} else {
current_crc_value = current_crc_value >>> 1;
}
}
}
current_crc_value = ~current_crc_value;
return current_crc_value & 0xFFFF;
}
我得到结果 FA DE 不是 [27] [56]
使用此代码:
public static void main(String[] args) {
int crc = 0x0000;
int polynomial = 0x1081;
// byte[] testBytes = "123456789".getBytes("ASCII");
// byte[] array = args[0].getBytes();
byte[] array = new byte[3];
array[0] = (byte) 0xFC;
array[1] = (byte) 0x05;
array[2] = (byte) 0x11;
for (byte b : array) {
for (int i = 0; i < 8; i++) {
boolean bit = ((b >> (7-i) & 1) == 1);
boolean c15 = ((crc >> 15 & 1) == 1);
crc <<= 1;
if (c15 ^ bit) crc ^= polynomial;
}
}
crc &= 0xffff;
System.out.println("CRC16-CCITT = " + Integer.toHexString(crc));
}
我知道了CRC16-CCITT = 8dca
使用此代码:
private final int polynomial = 0x1081;
private int[] table = new int[256];
public int ComputeChecksum(int[] bytes) {
int crc = 0xffff;
for (int i = 0; i < bytes.length; ++i) {
int index = (crc ^ bytes[i]) % 256;
crc = (crc >> 8) ^ table[index];
}
return crc;
}
public CRC162() {
int value;
int temp;
for (int i = 0; i < table.length; ++i) {
value = 0;
temp = i;
for (byte j = 0; j < 8; ++j) {
if (((value ^ temp) & 0x0001) != 0) {
value = (value >> 1) ^ polynomial;
} else {
value >>= 1;
}
temp >>= 1;
}
table[i] = value;
}
}
public static void main(String[] args) {
CRC162 c = new CRC162();
int[] arr = new int[]{0xFC, 0x05, 0x11};
System.out.println(Integer.toHexString(c.ComputeChecksum(arr)));
}
我知道了521
希望有人可以帮助我。我需要这个来与使用 ID003 协议的设备进行通信。
编辑: 在http://www.lammertbies.nl/comm/info/crc-calculation.html 使用这个在线计算器输入 FC0511 我从 CRC-CCITT (Kermit) 得到 0x2756。
【问题讨论】:
-
你确定^ operator 做你想做的事吗?
-
我不确定,我在stackoverflow和javaranch论坛上找到了这个功能。
-
我认为有一个定义问题:CCITT-CRC 的表示实际上是 x^16 + x^12 + x^5 + 1,但这给出的是 0x1021 而不是 0x1081(来源 Wikipedia on CRC
-
看来CRC有很多变种...你确定你想要的是对于这个数组[0xFC] [05] [11]的结果需要是 [27] [56]。因为根据在lammertbies.nl/comm/info/crc-calculation.html 找到的 progs,它不是标准的 CCITT CRC,而是 Kermit 变体。
-
@SergeBallesta,根据reveng.sourceforge.net/crc-catalogue/16.htm,Kermit 变体是“真正的”CCITT-CRC。
标签: java calculator polynomial-math crc16