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.

From byte array to string

// To convert a byte array bytes to a string returnStr 
// To remove a null character at the end
var returnStr = String.fromCharCode.apply(String, bytes ).replace(/\0/g,'');

From 2 bytes to unsigned integer number

// Sample usage: Hex 1235 => number=4661
var number = bytes[0] << 8 | bytes[1]

From 4 bytes to unsigned long number

// Sample usage: Hex 00000dc8 => number=3528
var number = bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[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));

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));

From 2 bytes to simple unsigned float number

// Sample usage: Hex 1235 => number=4661 => 466.1
var number = (bytes[0] << 8 | bytes[1]) / 10;
5 1 vote
Article Rating
Subscribe
Notify of
0 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments

Want to test LoRaWAN?

Subscribe Easy LoRaWAN Cloud to try this guide on your LoRaWAN gateways and nodes.
We will help you to get started and troubleshooting.

Thanks for the guides?

If this guide saves your days, you can give us a cup of coffee.
This is one-time donation.
Thank you for supporting us.