在java中从字符数组和字节数组中提取特定字节
我有一个包含十六进制值的字符数组。它包含6个字节。我已经计算了这6个字节的crc,函数返回int值。 这是代码在java中从字符数组和字节数组中提取特定字节,java,binary,byte,crc,crc16,Java,Binary,Byte,Crc,Crc16,我有一个包含十六进制值的字符数组。它包含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 = C
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);
}
我的问题是
char buffer[] and crcresult
在单字节数组中 0X1 0X5 0X0 0X6 0X0 0X0 0X0 0X0 0X2d 0Xcb
其中前6个字节是从字符数组转换的字节,最后4个字节是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
如果你需要它的小端顺序,只需调整相应的任务
我不清楚为什么要使用字符数组来表示字节。是的,
crcresult
是32位,因为它的类型是int
。如果需要16位数据类型,请改用
但是,使用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
有关更多详细信息,请参阅。谢谢您的回复。bu代码在System.arraycopy行的CRC.CRCLikeC.main(CRCLikeC.java:93)处的java.lang.System.arraycopy处将错误显示为“线程中的异常”java.lang.ArrayStoreException。我们是否需要添加其他内容才能正常工作。抱歉,我以前的代码有错误。我把它修好了。之前我是从char[]复制到byte[],现在它是固定的。你能再试一次吗?