But: you should not always subtract that, as that would not work for positive values. Only subtract when the value exceeds the maximum of a signed short, that is: 32767 or 0x7FFF. Of if the leftmost bit of the MSB is 1, so if (bytes[2] & 0x80)
.
As JavaScript bitwise operations always assume 32 bits signed integers, the magic word is sign extension:
// Sign-extend to 32 bits to support negative values, by shifting
// 24 bits to the left (16 too far), followed by a sign-propagating
// right shift of 16 bits, to effectively shift 8 bits:
retValue.x1 = bytes[2]<<24>>16 | bytes[3];
(Also note that I used the bitwise OR rather than arithmetic addition, which saves you from the parentheses.)