Javascript unsigned short to signed short

末鹿安然 提交于 2019-12-13 14:23:20

问题


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/



来源:https://stackoverflow.com/questions/7461204/javascript-unsigned-short-to-signed-short

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!