Johannes Deger
Johannes Deger

Reputation: 33

Interpret 16bit two's complement in javascript (nodejs)

Hello dear swarm intelligence,

One of my current private projects is in the field of the internet of things, specifically LoRaWan and TTN. For easy data-handling I decided to use node-red which is a node-js based flow tool to process the received data. This is the first time ever I have encoutered contact with the javascript world (apart from minor reading ;)). Here's the problem:

I am transmitting an C-Style int16_t signed type devided into two 8-bit nibbles via ttn. On the receiving site I want to merge these two nibbles again into a signed 16 bit type. Well the problem is that javascript only supports 32-bit intergers which means by simply mergin them via bitwise operations like this:

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

I lose the signed information and just get the unsigned interpretation of the data, since it is not stored in a 32-bit two's complement. Since I am not yet firmly familiar with the javascript "standard library" this seems like a hard problem for me! Any help will be appreciated

Upvotes: 3

Views: 2749

Answers (1)

Endenite
Endenite

Reputation: 390

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;
}

Note that this still stores the value as a signed 32-bit integer, but with the right value.

Upvotes: 2

Related Questions