2017-06-01 105 views
0

我有我的计算的字节数组CRC16一个C#代码:转换CRC16 C#代码到Java CRC16

public static byte[] CalculateCRC(byte[] data) 
    { 
     ushort crc = 0; 
     ushort temp = 0; 

     for (int i = 0; i < data.Length; i++) 
     { 
      ushort value = (ushort)data[i]; 

      temp = (ushort)(value^(ushort)(crc >> 8)); 
      temp = (ushort)(temp^(ushort)(temp >> 4)); 
      temp = (ushort)(temp^(ushort)(temp >> 2)); 
      temp = (ushort)(temp^(ushort)(temp >> 1)); 

      crc = (ushort)((ushort)(crc << 8)^(ushort)(temp << 15)^(ushort)(temp << 2)^temp); 
     } 
     byte[] bytes = new byte[] { (byte)(CRC >> 8), (byte)CRC }; 
     return bytes; 
    } 

现在,我要重复在Java中完全一样的逻辑。但是,我写的下面的代码并没有给我预期的结果。

public static byte[] calculateCrc16(byte[] data) 
{ 
    char crc = 0x0000; 
    char temp; 
    byte[] crcBytes; 

    for(int i = 0; i<data.length;++i) 
    { 
     char value = (char) (data[i] & 0xFF); 

     temp = (char)(value^(char) (crc >> 8)); 
     temp = (char)(temp^(char) (temp >> 4)); 
     temp = (char)(temp^(char) (temp >> 2)); 
     temp = (char)(temp^(char) (temp >> 1)); 

     crc = (char) ((char)(crc << 8)^ (char)(temp <<15)^(char)(temp << 2)^temp); 
    } //END of for loop 

    crcBytes = new byte[]{(byte)((crc<<8) & 0x00FF), (byte)(crc & 0x00FF)}; 
    return crcBytes; 
} 

我无法弄清楚我的java代码有什么逻辑错误。任何帮助,将不胜感激。

测试数据是以下字节数组

{ 
48, 48, 56, 50, 126, 49, 126, 53, 53, 53, 126, 53, 126, 54, 48, 126, 
195, 120, 202, 249, 35, 221, 44, 162, 7, 191, 207, 64, 31, 144, 88, 
62, 201, 51, 191, 234, 82, 62, 226, 1, 69, 186, 192, 26, 171, 197, 229, 
247, 180, 155, 255, 228, 86, 213, 255, 254, 215, 89, 53, 96, 186, 49, 135, 
185, 0, 19, 103, 168, 44, 8, 203, 154, 150, 237, 234, 176, 110, 113, 154 
} 

应提前返回{86,216}

谢谢!

+0

Java类型字节的范围是-128,...,127。有了您的测试数据,我甚至无法编译。 –

+0

@TobiasBrösamle将上面的示例作为int数组使用(byte)intValue将其转换为字节数组。 –

+0

我没有得到C#代码的结果。 –

回答

0

A ushort是16位,而char是8位。所以你的Java版本不可能有相同的中间值。使用int,它可以存储16位值就好了。

如果使用int,则需要将结果截断为每个循环的16位,因此在循环结束前放入crc &= 0xffff;