Signed int in javascript codec


#1

Hi,

I’m using an arduino that encodes uint16_t variable data and sends it to a lora sensor B-L072Z-LRWAN1 via “at command”,
One of the variable contain negatif number, so when i decode the byte array in the javascript codec, i obaint the wrong value of this variable, but all the other variable are correcte.

my javascrip decode :

     function Decode(fPort, bytes) {

          var puissance_bat    = bytes[0]  << 8  | bytes[1]   ;
          var polo = puissance_bat.valueOf();
          var niveau_bat       = bytes[2]  << 24 | bytes[3]   ;
          var tension_bat      = bytes[4]  << 40 | bytes[5]   ;
          var temperature_bat  = bytes[6]  << 56 | bytes[7]   ;
          var temperature_pcb  = bytes[8]  << 72 | bytes[9]   ;
          var consigne_courant = bytes[10] << 88 | bytes[11]  ;

        return {
         "puissance_bat": polo ,
         "niveau_bat": niveau_bat ,
         "tension_bat": tension_bat ,
         "temperature_bat": temperature_bat ,
         "temperature_pcb": temperature_pcb ,
         "consigne_courant": consigne_courant ,
      };
    }

result :slight_smile:
bat

the variable “puissance_bat” should be ecale to "-20 " , maybe there something to do in decoding for signed data ?


#2

A simple solution would in pseudocode be something like

if val >= 32768
   val = 65536-val

Provided that your initial interpretation of the bytes is as unsigned values before assembling them into a multi-byte unsigned word - which you then want to re-interpret as a signed 2’s complement value.


#3

hello,

here a part of code in node.js which convert an hex into a decimal and applied a mask according to the sign.

  // Convert the hex values into decimal and apply the calculations

  const altitude = Number(hexAlt) / 100;

  x = parseInt( hexAccX, 16);
  if (( x & 0x8000) > 0) {
  x =  x - 0x10000;
  }
  const accelerometerX = Number(x) / 1;

  y = parseInt( hexAccY, 16);
  if (( y & 0x8000) > 0) {
  y =  y - 0x10000;
  }
  const accelerometerY = Number(y) / 1;

  z = parseInt( hexAccZ, 16);
  if (( z & 0x8000) > 0) {
  z =  z - 0x10000;
  }
  const accelerometerZ = Number(z) / 100;

#4

@cstratton thanks, your solution really help me, i think that my uint16_t are overflow, i will put my variable to uint32_t.
@julien i will try to use your exemple , thanks.