Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a UINT16 value into a UINT8 array[2]

Tags:

c++

endianness

This question is basically the second half to my other Question

How can I convert a UINT16 value, into a UINT8 * array without a loop and avoiding endian problems.

Basically I want to do something like this:

UINT16 value = 0xAAFF;
UINT8 array[2] = value;

The end result of this is to store value into a UINT8 array while avoiding endian conversion.

UINT8 * mArray;
memcpy(&mArray[someOffset],&array,2);

When I simply do memcpy with the UINT16 value, it converts to little-endian which ruins the output. I am trying to avoid using endian conversion functions, but think I may just be out of luck.

like image 812
dp. Avatar asked Aug 17 '09 17:08

dp.


1 Answers

How about

UINT16 value = 0xAAFF;
UINT8 array[2];
array[0]=value & 0xff;
array[1]=(value >> 8);

This should deliver the same result independent of endianness.

Or, if you want to use an array initializer:

UINT8 array[2]={ value & 0xff, value >> 8 };

(However, this is only possible if value is a constant.)

like image 158
Martin B Avatar answered Sep 30 '22 15:09

Martin B