Reputation: 11
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)
Upvotes: 0
Views: 870
Reputation: 304
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;
Upvotes: 0
Reputation: 58868
(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.
Upvotes: 3