I found that the accepted answer was nearly correct, except i'd run into a bug where sometimes the top byte of the result would be 0xff
...
I realized this was because of C sign extension. if the second char is >= 0x80
, then converting 0x80
to a short becomes 0xff80
. Performing an 'or' of 0xff80
with anything results in the top byte remaining 0xff
.
The following solution avoids the issue by zeroing out the top byte of b during its implicit conversion to a short.
short c = (((short)a) << 8) | (0x00ff & b);