This guide will instruct you to convert bytes into common number formats and use them in the codec of Device-profile.

  • Converter from hex to other number formats: here
  • Converter between hex and other formats: here
  • The convertion function must be placed on the start of the codec.

1. From 2 bytes to unsigned integer number

var number = bytes[0] << 8 | bytes[1]

// Sample usage: Hex 1235 => number=4661

2. From 4 bytes to unsigned long number

var number = bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3]

// Sample usage: Hex 00000dc8 => number=3528

3. From 4 bytes (2 registers) to float

// Float is 32-bit (4 bytes)
function hex2float(num) {
var sign = (num & 0x80000000) ? -1 : 1; // 1 bit. To check the sign bit on most left
var exponent = ((num >> 23) & 0xff) - 127; // 8 bits. 8 right bits. -127 to 128
var mantissa = 1 + ((num & 0x7fffff) / 0x7fffff); // 23 bits
return parseFloat((sign * mantissa * Math.pow(2, exponent)).toFixed(3));
}

// Sample usage: 11.11
var hex = 0x4131c28f;
alert(hex2float(hex));

4. From 8 bytes (4 registers) to double

// Double is 64-bit (8 bytes)
function hex2double(left, right) {
var sign = (left & 0x80000000) ? -1 : 1; // 1 bit. To check the sign bit on most left
var e = (left >> 52 - 32 & 0x7ff) - 1023
return (left & 0xfffff | 0x100000) * 1.0 / Math.pow(2,52-32) * Math.pow(2, e) + right * 1.0 / Math.pow(2, 52) * Math.pow(2, e)
}

// Sample usage: 0x40fb207000000001 => 1111111.00000000001
alert(hex2double(0x40fb2070, 0x00000001));

5. From 2 bytes to simple unsigned float number

var number = (bytes[0] << 8 | bytes[1]) / 10;

// Sample usage: Hex 1235 => number=4661 => 466.1

Want to VISUALIZE data?

Subscribe Easy LoRaWAN Cloud to try all the guides and visualize data from your LoRaWAN nodes.
We will actively assist you to deploy your initial LoRaWAN setup.