在javascript(nodejs)中解释16位二进制补码

时间:2017-06-18 12:37:33

标签: javascript node.js signed twos-complement 16-bit

你好亲爱的群体智慧,

我目前的一个私人项目是物联网领域,特别是LoRaWan和TTN。为了便于数据处理,我决定使用node-red作为基于node-js的流量工具来处理接收到的数据。 这是我第一次与javascript世界接触(除了小读;))。这就是问题所在:

我正在通过ttn传输一个C-Style int16_t签名类型,分为两个8位半字节。在接收站点上,我想将这两个半字节再次合并为带符号的16位类型。好吧问题是javascript只支持32位内插,这意味着只需通过按位操作来优化它们:

newMsg.payload=(msg.payload[1]<<8)|(msg.payload[0]);

我丢失了签名信息,只是得到了数据的无符号解释,因为它没有存储在32位二进制补码中。 因为我还不熟悉javascript&#34;标准库&#34;这对我来说似乎是个难题! 任何帮助将不胜感激

1 个答案:

答案 0 :(得分:1)

var unsignedValue = (msg.payload[1] << 8) | (msg.payload[0]);

if (result & 0x8000) {
    // If the sign bit is set, then set the two first bytes in the result to 0xff.
    newMsg.payload = unsignedValue | 0xffff0000;
} else {
    // If the sign bit is not set, then the result  is the same as the unsigned value.
    newMsg.payload = unsignedValue;
}

请注意,这仍然将值存储为带符号的32位整数,但值正确。