将CRC16 C#代码转换为Java CRC16

时间:2017-06-01 12:28:56

标签: java c# crc16

我有一个C#代码,用于计算字节数组上的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}

提前致谢!

1 个答案:

答案 0 :(得分:0)

ushort是16位,而char是8位。因此,您的Java版本不可能具有相同的中间值。使用int,可以很好地存储16位值。

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