Search code examples
cstringhexendiannesscrc16

Separate data and store in array


I'm having problem fixing the endianness of the value that I got.

What I'm thinking is separate a WORD to two, convert them to hex, and store them in an array.

The WORD is the "crc_data" that is return to my previous question(which has been answered).

MODBUS RTU CRC16 calculation

For example:

I got a "result" data from the code of:

crc_data = 0A95

*Note: crc_data is datatype WORD

What I'm thinking is separate them into two, and make them as hex. Like this:

value_1 = 0x95
value_2 = 0x0A

Is there a way to do that? I read something about "BITWISE" operation, but I'm not sure if that's the way to do it.


Solution

  • You could cast to a char*. You would do it like this:

    crc_data = 0x0A95
    const unsigned char *k = (const unsigned char*) &crc_data;
    value_1 = k[0];
    value_2 = k[1];
    

    The char pointer just lets you treat the data as though it was a string of bytes. You can then read them with the [] notation.

    Another way is to use math to get the upper and lower parts. The bitshift operator << will shitf your data down 8 bits. It's the same as dividing by 256.

    crc_data = 0x0A95;
    value_1 = crc_data & 0xFF;
    value_2 = (crc_data >> 8) & 0xFF;
    

    Another option is to use a union. Basically there are a lot of ways to do this.