簡體   English   中英

將CRC16 C#代碼轉換為Java CRC16

[英]Convert CRC16 C# code to Java 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}

提前致謝!

ushort是16位,而char是8位。 因此,您的Java版本不可能具有相同的中間值。 使用int ,它可以存儲16位值。

如果使用int,則對於每個循環,您都需要將結果截斷為16位,因此放入crc &= 0xffff; 在循環結束之前。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM