# Payload Decoder

**URL:** <https://www.thethingsnetwork.org/forum/t/payload-decoder/17221>\
**Category:** Uncategorized\
**Created:** [August 27, 2018, 1:03pm UTC](https://www.thethingsnetwork.org/forum/t/payload-decoder/17221 "2018-08-27T13:03:36Z")\
**Posts on this page:** 1\
**Showing post:** 4

<div class="post-metadata">

**Author:** ![arjanvanb](https://www.thethingsnetwork.org/forum/user_avatar/www.thethingsnetwork.org/arjanvanb/32/46626_2.png) [@arjanvanb](https://www.thethingsnetwork.org/forum/u/arjanvanb)\
**Post date:** [August 28, 2018, 3:47pm UTC](https://www.thethingsnetwork.org/forum/t/payload-decoder/17221/4 "2018-08-28T15:47:40Z")

</div>

You should not change the `bytesToFloat` function; that function does not need to know how your payload is formatted (except if you change MSB/LSB), but just wants 4 bytes for its input. So, simply use [the original `bytesToFloat`](https://www.thethingsnetwork.org/forum/t/decode-float-sent-by-lopy-as-node/8757/2) along with:

```javascript
// Test with 0213343F4A6666D2414C00D207424DB750C247 for 26.299999237060547
// outputted with one decimal as 26.3:
return {
  sensorID: bytes[4],
  // Take bytes 5 to 9 (not including), convert to float, convert to a
  // string with one decimal, and use the unary plus-operator to cast
  // the string result of toFixed to a proper number:
  temp: +bytesToFloat(bytes.slice(5, 9)).toFixed(1)
};

```

Alternatively, showing why `bytesToFloat` should not be adjusted to a specific sensor, but can be used for multiple values, assuming those are floats too, and using [the `x++` postfixed increment operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Increment_()) to keep track of the bytes that have been handled:

```javascript
// Decode all, for readable code.
// Just assuming some encoding here!
// Skip bytes 0 and 1
var b = 2;
var batt = (bytes[b++]<<8 | bytes[b++]) / 1000;
var tempId = bytes[b++];
var temp = +bytesToFloat(bytes.slice(b, b+=4)).toFixed(2);
var humiId = bytes[b++];
var humi = +bytesToFloat(bytes.slice(b, b+=4)).toFixed(2);
var pressId = bytes[b++];
var press = +bytesToFloat(bytes.slice(b, b+=4)).toFixed(2);

// Only return the values we're interested in:
return {
  batt: batt,
  sensorID: tempId,
  temp: temp
};

```

Of course, the repetitive use of `toFixed` could also be added to `bytesToFloat` instead:

```javascript
return +f.toFixed(2);

```

Also, please see [How do I format my forum post?](https://www.thethingsnetwork.org/forum/t/how-do-i-format-my-forum-post/8735) and please adjust the comments when you change the code!

---

_[View the full topic](https://www.thethingsnetwork.org/forum/t/payload-decoder/17221)._
