Trouble with decoding uint64

Hi everyone. I have trouble with decoding uint64.
For example I need to decode next sequence of bytes.
00 00 00 2E FC 83 ED 7D 00 00 00 BE
where 00 00 00 2E FC 83 ED 7D is the value in unsigned int 64 format
I am trying to decode it with this code

function Decoder(bytes) {

  var s=bytes[0] << 56 |bytes[1] << 48 |bytes[2] << 40|bytes[3] << 32|bytes[4] << 24|bytes[5] << 16|bytes[6] << 8|bytes[7];
  var t = bytes[8] << 24 |bytes[9] << 16 |bytes[10] << 8 |bytes[11];

  return {
    serial: s,
    temperature: t 
  }
}

But I get wrong decoded values
{
“serial”: -58462849,
“temperature”: 190
}
serial must be 201805000061.
I just cant understand what is wrong here.

Playing some more time I discovered that next code decode sequence in wright way
function Decoder(bytes) {

  var sh = bytes[0] << 24 |bytes[1] << 16 |bytes[2] << 8 |bytes[3];
  var sl = bytes[4] << 24 |bytes[5] << 16 |bytes[6] << 8 |bytes[7];
  sh=(sh*0x100000000);
  var s=sh + sl+0x100000000;
  var t = bytes[8] << 24 |bytes[9] << 16 |bytes[10] << 8 |bytes[11];

  return {
    serial: s,
    temperature: t 
  }
}

The result is
{
“serial”: 201805000061,
“temperature”: 190
}
But this code is too bulky and ugly. Help me please how to decode uint64 in correct way

A payload format Decoder in TTN Console is a JavaScript function, and JavaScript has no notion of 64 bits integers. Instead, all numbers are floating point, and have a maximum integer precision of 53 bits. (So, your “bulky” version will fail when not starting with 0x0000 like in your example.) On top of that, JavaScript’s bitwise operators always work on 32 bits numbers.

You’ll have to convert the bytes into a string value, probably easiest done in a hexadecimal represenation:

var s = bytes.slice(0, 8).map(function(b) {
  // Return the byte in a hexadecimal representation with a leading zero
  return ("0" + b.toString(16)).substr(-2);
}).join("").toUpperCase();

As an aside: the LoRaWAN DevEUI can probably take care of supplying (or mapping to) the serial you’re after? Saves you 8 bytes in the application’s payload.

This topic was automatically closed 60 days after the last reply. New replies are no longer allowed.