0

How do I merge two unsigned chars into a single unsigned short in c++. The Most Significant Byte in the array is contained in array[0] and the Least Significant Byte is located at array[1] . (Big endian)

thecoder
  • 11
  • 2

2 Answers2

3

(array[0] << 8) | array[1]

Note that an unsigned char is implicitly converted ("promoted") to int when you use it for any calculations. Therefore array[0] << 8 doesn't overflow. Also the result of this calculation is an int, so you may cast it back to unsigned short if your compiler issues a warning.

user253751
  • 57,427
  • 7
  • 48
  • 90
0

Set the short to the least significant byte, shift the most significant byte by 8 and perform a binary or operation to keep the lower half

unsigned short s;
s = array[1];
s |= (unsigned short) array[0] << 8;
Ruben
  • 194
  • 2
  • 11