繁体   English   中英

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

[英]Extract certain byte from char array and byte array in java

我有一个包含十六进制值的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转换为字节。 但是计算的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 

    在一个字节数组中。

上面代码的输出是

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

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

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数组表示字节。

是的, 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM