我有一个如下所示的 Java CRC16 函数,我需要它返回一个 4 长度的字母数字结果。但有时它只返回一个 3 长度的字母数字。为什么?我将此 CRC 与计算 CRC 的 C 应用程序进行交叉比较,通常它是相同的 CRC,但 JAVA 有时会返回一个 3 个字符的结果,这会引发异常。为什么?
int crrc = 0xFFFF; // initial value
int polynomial = 0x1021; // 0001 0000 0010 0001 (0, 5, 12)
String str = "0009";
byte []by = x; // x is the byte array from args
for (byte b : by) {
for (int i = 0; i < 8; i++) {
boolean bit = ((b >> (7-i) & 1) == 1);
boolean c15 = ((crrc >> 15 & 1) == 1);
crrc <<= 1;
if (c15 ^ bit) crrc ^= polynomial;
}
}
crrc &= 0xffff;
System.out.println(crrc);
System.out.println("CRC16-CCITT = " + Integer.toHexString(crrc) + " " + Integer.toHexString(crrc).length());