# Cayenne Lat/Lon Decoder

**URL:** <https://www.thethingsnetwork.org/forum/t/cayenne-lat-lon-decoder/28110>\
**Category:** Application Development\
**Created:** [July 15, 2019, 4:35pm UTC](https://www.thethingsnetwork.org/forum/t/cayenne-lat-lon-decoder/28110 "2019-07-15T16:35:19Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![wrldtvlr](https://www.thethingsnetwork.org/forum/user_avatar/www.thethingsnetwork.org/wrldtvlr/32/35697_2.png) [@wrldtvlr](https://www.thethingsnetwork.org/forum/u/wrldtvlr)\
**Post date:** [July 15, 2019, 4:35pm UTC](https://www.thethingsnetwork.org/forum/t/cayenne-lat-lon-decoder/28110/1 "2019-07-15T16:35:19Z")

</div>

I am trying to write a decoder for a device that is reporting position in Cayenne LPP format. The basic conversion

decode.lat = (bytes[2] \<\< 16) | (bytes[3] \<\< 8 | bytes[4] ) ;  
decode.lat = decode.lat / 10000 ;  
decode.lon = (bytes[5] \<\< 16) | (bytes[6] \<\< 8) | bytes[7];  
decode.lon = decode.lon / 10000;

works, but does not take into consideration negative values. Given the following test payload

01 88 07 31 1E F0 C8 29 00 DA 5C 02 02 01 8E 03 67 01 40

I think there needs to be logic that looks at the high bit of the first byte of the lat/log triplet to determine whether it is negative, but I haven’t been able to write anything that works. Can someone offer a suggestion?

---

<div class="post-metadata">

**Author:** ![wrldtvlr](https://www.thethingsnetwork.org/forum/user_avatar/www.thethingsnetwork.org/wrldtvlr/32/35697_2.png) [@wrldtvlr](https://www.thethingsnetwork.org/forum/u/wrldtvlr)\
**Post date:** [July 15, 2019, 7:51pm UTC](https://www.thethingsnetwork.org/forum/t/cayenne-lat-lon-decoder/28110/2 "2019-07-15T19:51:10Z")

</div>

And worked it out. Replace lines above with

decode.lat = (bytes[4] + (bytes[3]\<\<8) + (bytes[2]\<\<16) + (bytes[2] & 0x80 ? 0xFF\<\<24 : 0)) / 10000;  
decode.lon = (bytes[7] + (bytes[6]\<\<8) + (bytes[5]\<\<16) + (bytes[5] & 0x80 ? 0xFF\<\<24 : 0)) / 10000;
