2

16 進値を含む char 配列があります。これには 6 バイトが含まれます。これらの 6 バイトの crc を計算すると、関数は int 値を返します。これがコードです。

char buffer[] = {0x01,0x05,0x00,0x06,0x00,0x00};

byte[] bufferbyte = new String(buffer).getBytes();
for (byte bb : bufferbyte){
  System.out.format("0X%x ", bb);
}

int crcresult;
crcresult = CRC16(buffer,6); //crc calculation

byte[] crc_bytes = ByteBuffer.allocate(4).putInt(crcresult).array();

for (byte b : crc_bytes){
  System.out.format("0X%x ", b);
}

私の質問は

  1. intとして取得したcrcをバイトに変換するためにbytebufferを使用しました。ただし、計算された crc は 2 バイトではなく 4 バイトで格納されます。CRC 16 を計算しましたが、結果の crc は 32 ビットです。crcの計算で「int」を返してしまい、javaではintは32bitと書いてあるからだと思います。

    では、バイト バッファ (crc_bytes) または計算された int crc (crcresult) から 2 バイトだけを抽出する方法を説明します。

  2. 「char buffer[]」のバイトと計算されたcrcの2バイトを1バイト配列に入れました。どうすれば追加できますか

    char buffer[] and crcresult 
    

    1 バイト配列で。

上記のコードの出力は

 0X1 0X5 0X0 0X6 0X0 0X0 0X0 0X0 0X2d 0Xcb 

最初の 6 バイトは char 配列から変換されたバイトで、最後の 4 バイトは crc です。

4

2 に答える 2

1

ビッグ エンディアン順の crc の 2 バイトは、次のコマンドで取得できます。

byte[] crc_result = new byte[2];
crc_bytes[0] = (byte)(crcresult >> 8); // this are the high order 8 bits
crc_bytes[1] = (byte)crcresult; // this are the low order 8 bits

リトル エンディアン順で必要な場合は、それに応じて割り当てを調整してください。

バイトを表すために char 配列を使用する理由は明確ではありません。

于 2014-01-02T08:54:20.653 に答える
0

はい、crcresultタイプが 32 ビットであるためですint。16 ビットのデータ型が必要な場合は、代わりにshortを使用してください。

ただし、int 型を使用しても害はありません。32 ビットですが、最後の 16 ビットのみに CRC16 値が含まれます。これらの 2 バイトは、次のビット演算で抽出できます。

byte byte1 = (byte)((crcresult >> 8) & 0xFF); // first 8 bits of last 16 bits
byte byte0 = (byte)(crcresult & 0xFF);        // last 8 bits

結果をマージします。

byte[] merged = new byte[bufferbyte.length + 2];
System.arrayCopy(bufferbyte, 0, merged, 0, bufferbyte.length);  // copy original data buffer
merged[bufferbyte.length    ] = byte1;                      // append crc16 byte 1  
merged[bufferbyte.length + 1] = byte0;                      // append crc16 byte 2   

詳細については、 System.arrayCopyを参照してください。

于 2014-01-02T08:56:22.147 に答える