3

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

  • *Hello dear swarm intelligence,* +1 ;). theres no binary type in js. Its either a number ( 16bit floating point value or int ) or a string. – Jonas Wilms Jun 18 '17 at 12:43
  • Hey, Thanks for the answer. Interstingly there are bitwise operators in js, so I thought that maybe there might also be a way to interpret 16bit signed types. I was hoping for some perl-esque pack/unpack magic – Johannes Deger Jun 18 '17 at 12:48
  • I haven't played around with two's complement in a while, but I'd take a look here (https://stackoverflow.com/questions/9939760/how-do-i-convert-an-integer-to-binary-in-javascript) and here (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int16Array). I think that'll send you in the right direction... – javinor Jun 18 '17 at 12:50
  • I think it already has a solution here https://stackoverflow.com/questions/27911677/how-to-convert-a-binary-number-into-a-signed-decimal-number# – Jonas Wilms Jun 18 '17 at 12:51
  • Javascript supports bitwise operations on integers no larger than 4bytes. But, when dealing with large numbers, it's helpful to know that Javascript's Number type is actually IEEE754 (double precision). This gives you 52bits available for the integer and you can use Math (pow mostly) to help you emulate bitwise operations. – Reinsbrain Jun 18 '17 at 14:15

1 Answers1

2
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.

Endenite
  • 382
  • 6
  • 13