# Decoding a float value in a payload function

**URL:** <https://www.thethingsnetwork.org/forum/t/decoding-a-float-value-in-a-payload-function/4395>\
**Category:** Application Development\
**Created:** [December 10, 2016, 2:11pm UTC](https://www.thethingsnetwork.org/forum/t/decoding-a-float-value-in-a-payload-function/4395 "2016-12-10T14:11:04Z")\
**Posts on this page:** 1\
**Showing post:** 24

<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:** [June 3, 2017, 11:04am UTC](https://www.thethingsnetwork.org/forum/t/decoding-a-float-value-in-a-payload-function/4395/24 "2017-06-03T11:04:37Z")

</div>

> [@Jonathanmf](#):
>
> ```c
> byte buffer[8];
> float t = dht.readTemperature();
> float h = dht.readHumidity();
> dtostrf(t, 2, 1, buffer);
> dtostrf(h, 2, 1, &buffer[4]);
> 
> ```

This goes horribly wrong for any value that does not convert to exactly four characters. (If you found that code elsewhere, please refer the author to this answer…)

Instead, use [something like explained above](https://www.thethingsnetwork.org/forum/t/decoding-a-float-value-in-a-payload-function/4395/19):

```c
// Read sensor values and multiply by 100 to effectively keep 2 decimals
// Signed 16 bits integer, -32767 up to +32767
int16_t t = dht.readTemperature() * 100;
// Unsigned 16 bits integer, 0 up to 65535
uint16_t h = dht.readHumidity() * 100;

```

This can be encoded into just 4 bytes for the 2 values, using some “shifting” as explained in more detail in [Decrypting messages for dummies](https://www.thethingsnetwork.org/forum/t/decrypting-messages-for-dummies/4894/4):

```c
byte buffer[4];
buffer[0] = t >> 8;
buffer[1] = t;
buffer[2] = h >> 8;
buffer[3] = h;
LMIC_setTxData2(1, buffer, sizeof(buffer), 0);

```

And decoded like also explained in more detail in the link above:

```js
function Decoder(bytes, port) {
  var t = (bytes[0] & 0x80 ? 0xFFFF<<16 : 0) | bytes[0]<<8 | bytes[1];
  var h = bytes[2]<<8 | bytes[3];
  return {
    temperature: t / 100,
    humidity: h / 100
  }
}

```

You could probably even send humidity without any decimals, saving yet another byte:

```c
// Unsigned 8 bits integer, 0 up to 255
uint8_t h = dht.readHumidity();

```

…with:

```c
byte buffer[3];
buffer[0] = t >> 8;
buffer[1] = t;
buffer[2] = h;
LMIC_setTxData2(1, buffer, sizeof(buffer), 0);

```

…and:

```js
function Decoder(bytes, port) {
  var t = (bytes[0] & 0x80 ? 0xFFFF<<16 : 0) | bytes[0]<<8 | bytes[1];
  var h = bytes[2];
  return {
    temperature: t / 100,
    humidity: h
  }
}

```

---

_[View the full topic](https://www.thethingsnetwork.org/forum/t/decoding-a-float-value-in-a-payload-function/4395)._
