以下のような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());