2 Chars to Short in C

c, int, short, type-conversion

Solution

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);

Problem

I've got 2 chars. Char `128` and Char `2`. How do I turn these chars into the Short `640` in C? I've tried ``` unsigned short getShort(unsigned char* array, int offset) { short returnVal; char* a = slice(array, offset, offset+2); memcpy(&returnVal, a, 2); free(a); return returnVal; } ``` But that didn't work, it just displays it as `128`. What's the preferred method?

Original source