Javascript unsigned short到signed short [英] Javascript unsigned short to signed short
本文介绍了Javascript unsigned short到signed short的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码:
var v = [0xFF, 0xFF];
alert((v[0]<<8) | v[1]);
它会发出65535(最大卖空价值)的警报.
And it alerts 65535 (the max short value).
如何将这个字节数组视为有符号的short,并获取该数组的有符号值.
How can I treat this byte array as a signed short, and get the signed value of this array.
推荐答案
假定较高的位是符号:
var sign = v[0] & (1 << 7);
var i = ((v[0] & 0x7F) << 8) | v[1];
if (sign) {
i = -i;
}
如果您使用 Two's补语表示形式:
var i = (((v[0] << 8) | v[1]) << 16) >> 16);
左移16位将所有位向左移动;算术右移16位将在移位时照顾符号.(JavaScript使用32位整数进行移位操作.)
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.)
这篇关于Javascript unsigned short到signed short的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文