Question

I have an char array containing hex value. It contains 6 bytes. I have calculated the crc of these 6 bytes and the function returns int value. This is the code.

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);
}

My question are

  1. I have used bytebuffer to convert crc obtained as int into byte. But the calculated crc are stored in 4 byte instead of 2 byte. I have calculated CRC 16 but the resulting crc is 32 bit . I think it is because i have returned "int" in the crc calculation and it is written that in java an int is 32 bits.

    So How to extract only two bytes from the byte buffer (crc_bytes) or the calculated int crc (crcresult).

  2. I have put the bytes of the "char buffer[]" and two bytes of calculated crc in single byte array. How can we append

    char buffer[] and crcresult 
    

    in one byte array.

The output of above code is

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

Where first 6 bytes are bytes converted from char array and last 4 bytes are crc.

Was it helpful?

Solution 2

Yes, crcresult is 32 bits because it is of type int. If you want a 16bit data type, use short instead.

But, using int type does not do any harm. Although it is 32 bit, only last 16 bits will contain CRC16 value. You can extract those two bytes with following bitwise operations.

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

To merge the results.

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   

Refer System.arrayCopy for more details.

OTHER TIPS

The two bytes of the crc in big endian order can be fetched with

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

If you need it in little endian order just adapt the assignments accordingly.

It is not clear to me why you use a char array to represent bytes.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top