2017-06-01 47 views
0

JavaのCRC16に変換:今すぐはCRC16 C#のコードは、私は私のバイト配列にCRC16を計算し、C#のコード持って

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

ushortは16ビットであるのに対して、charは8ビットである。したがって、あなたのJavaバージョンが同じ中間値を持つことは不可能です。 intを使用してください。これは16ビット値をうまく保存できます。

intを使用する場合、ループの最後の前にcrc &= 0xffff;に入れて、結果を各ループの16ビットに切り捨てる必要があります。

関連する問題