Decoder function hex - dec

can someone help me setup a decoder function which can extract second and third byte from below payload and convert to decimal.

5408C10000000000000000000001F303E8000056B032BE006E

(above payload is in hex)

Hi @abhishek2101,

I’m assuming that the 2 bytes represent a 16bit unsigned integer.

hex 08C1 = dec 2241.

Javascript for payload decoder on TTN core is something like:

function Decoder(bytes, port) {
var decoded = {};
…
decoded.yournumber = (bytes[1] << 8) + bytes[2];
…
return decoded;
}

The bytes array starts at 0 so the second byte (08) is bytes[1] and the third byte (C1) is bytes[2].

Unless the value is little-endian, which is the native format of a majority of embedded systems today, though big endian is more common in standardized protocols. The asker doesn’t state which it is.

If it is little endian, then the value of the two bytes needs to be swapped when unpacking, so the [1] and [2] would change places in the expression.

1 Like

great, this works.

additionally, since this is a stream of bytes, how can I extract the last four bytes also and decode all of them at the same time ?

Hi @abhishek2101, it looks to me like the payload is 25 bytes long, so bytes[0] … bytes[24]. @cslorabox is, of course, correct. The decoder script that I suggested is for big-endian.

The last 4 bytes are bytes[21] … bytes[24] and are hex 32BE006E = dec 851312750.

Assuming that this is a 4 byte big-endian unsigned integer, a simple mod to the decoder Javascipt:

…
decoded.firstnumber = (bytes[1] << 8) + bytes[2];
decoded.secondnumber = (bytes[21] << 24) + (bytes[22] << 16) + (bytes[23] << 8) + bytes[24];
…

This should return both “firstnumber”:2241 and “secondnumber”:851312750.

1 Like

This topic was automatically closed 60 days after the last reply. New replies are no longer allowed.