最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

arrays - Javascript unsigned short to signed short - Stack Overflow

programmeradmin1浏览0评论

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.

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.

Share Improve this question edited Sep 18, 2011 at 19:17 Charles 51.5k13 gold badges106 silver badges144 bronze badges asked Sep 18, 2011 at 11:36 Timo WillemsenTimo Willemsen 8,86711 gold badges55 silver badges83 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 5

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/p4TQw/1/


If you use the Two's plement 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/p4TQw/3/

发布评论

评论列表(0)

  1. 暂无评论