如何将此工作 Java 计算 CRC16 的脚本代码翻译成 Java

How to translate this working JavaScript Code to calculate CRC16 into Java

我需要为像这样的十六进制代码计算 CRC16: 08010000016B40D8EA30010000000000000000000000000000000105021503010101425E0F01F10000601A014E000000000000000001

上述十六进制字符串的预期结果是 0000C7CF ( 51151 )

我有这个有效的 Java脚本实现,我正在尝试将其转换为 Java:

var hex = "08010000016B40D8EA30010000000000000000000000000000000105021503010101425E0F01F10000601A014E000000000000000001";

var str = '';
for (var i = 0; i < hex.length; i += 2){ 
  str += String.fromCharCode( parseInt(hex.substr(i, 2), 16) );
}

var crc = 0x0000;
var poly = 0xA001;

for (var pos = 0; pos < str.length; pos++) {
  crc ^= str.charCodeAt(pos);
  for (var i = 8; i !== 0; i--) {
    if ((crc & 0x0001) !== 0) {
      crc >>= 1;
      crc ^= poly;
    } else
      crc >>= 1;
  }
}
console.log( crc );
console.log( crc.toString(16) );

我在 Java 中的当前实现如下所示:

String hex = "08010000016B40D8EA30010000000000000000000000000000000105021503010101425E0F01F10000601A014E000000000000000001";
byte[] arr = Hex.decodeHex( hex );
long polynomial = 0xA001;
long crc = 0x0000;
for (byte b : arr) {
    crc ^= b;
    for (int i = 8; i != 0; i--) {
        if ((crc & 0x01) != 0) {
            crc >>= 1;
            crc ^= polynomial;
        } else {
            crc >>= 1;
        }
    }
}
System.out.println( crc ); // -37776

不计算预期值。我做错了什么?

更改以下行

crc ^= b

crc ^= (b & 0xff)

在java中,byte的范围是-128到127,所以你必须把它设为无符号。