How can I convert negative binary number to int?

parseInt works on variable-length strings as input, which means that it cannot recognize the most significant bit as a sign bit. In other words: It parses binary strings like decimal strings, using a - as sign; so you have to use a different method than parseInt.

What hinders you from taking that 16-bit value and just pass it as unsigned? You'd just have to check whether the value coming in to your javascript is bigger than 32767, then do the two-complement conversion manually:

Your incoming numbers range would then be 0..20000 for positive "originals" and 45536..65535 for the original range -20000..-1 (if I'm thinking correct right now, I didn't verify that). This would mean that conversion is easy:

if( number > 32767 ) {
  number = -65536 + number;
}

Or, for any binary number type (that is smaller than the number size of the language you're working in):

if( number > SIGNED_MAX_INT ) {
  number = -(UNSIGNED_MAX_INT+1) + number;
}

(Those constants don't exist as written, they're more like pseudo code here)


First, it is REALLY bad practice to create new msg objects in function nodes, you should be just updating the msg.payload value and passing on the original object.

Next the easiest way to do this will be to work with a Buffer

e.g.

var b = Buffer(4)
b.writeUInt32BE(msg.playload)
msg.payload = b.readInt32BE()

return msg;

A join node in manual mode can combine the 2 smaller buffers into one of 16bits in length.