Javascript unsigned short to signed short

2019-07-04 11:11发布

问题:

I have the following code:

var v = [0xFF, 0xFF];
alert((v[0]<<8) | v[1]);

And it alerts 65535 (the max short value).

How can I treat this byte array as a signed short, and get the signed value of this array.

回答1:

Assuming the higher bit is the sign:

var sign = v[0] & (1 << 7);
var i = ((v[0] & 0x7F) << 8) | v[1];
if (sign) {
    i = -i;
}

http://jsfiddle.net/p4TQw/1/


If you use the Two's complement representation:

var i = (((v[0] << 8) | v[1]) << 16) >> 16);

The 16 bits left shift moves all bits to the left; and the arithmetic 16 bits right shift takes care of the sign while shifting. (Javascript uses 32 bits integers for shift operations.)

http://jsfiddle.net/p4TQw/3/