从java中的char数组和字节数组中提取某些字节

时间:2014-01-02 08:43:52

标签: java binary byte crc crc16

我有一个包含十六进制值的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. 我使用bytebuffer将获得的crc转换为byte。但计算出的crc存储在4个字节而不是2个字节中。我已经计算了CRC 16,但得到的crc是32位。我认为这是因为我在crc计算中返回了“int”,并且在java中写入int为32位。

    那么如何从字节缓冲区(crc_bytes)或计算出的int crc(crcresult)中只提取两个字节。

  2. 我把“char buffer []”的字节和两个字节的计算crc放在单字节数组中。我们如何追加

    char buffer[] and crcresult 
    

    在一个字节数组中。

  3. 上述代码的输出是

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

    前6个字节是从char数组转换的字节,最后4个字节是crc。

2 个答案:

答案 0 :(得分:1)

可以使用

获取大端序的crc的两个字节
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数组来表示字节。

答案 1 :(得分:0)

是的,crcresult是32位,因为它是int类型。如果您需要16位数据类型,请改用short

但是,使用int类型不会造成任何伤害。虽然它是32位,但只有最后16位将包含CRC16值。您可以通过以下按位操作来提取这两个字节。

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