From big integer to byte array.

Hello there,

here is my problem:

i need to send gps coordonates through an array of bytes: Latitude (4 bytes) & Longitude (4 bytes).
Here is the thing:
let my latitude be 48.15278, i need to send an integer with the value : 4815278. (0x 00 49 79 AE) and it needs to be encoded into a 4 bytes array (no matter the value is).

I need to put this value into an array of bytes like this :

byte send[number_of_bytes] = { //previsou values....., 0x00, 0x49, 0x79, 0xAE, //....next values }.

I don't really figure out how to turn my integer to that kind of bytes array...

I've seen solution using highByte and lowByte but it seems to only work if you need two bytes array..
e.g.:
int myValue = 12500 // int value
byte high = highByte(myValue );
byte low = lowByte(myValue );

Thank you in advance,

quentinkb:
i need to send an integer with the value : 48.15278....

By definition, integers don't have values to the right of the decimal point. It can be 48 or 49, nothing in between.

My raw value is 48.15278 which is not an integer, that's why i need to send : 4815278

This works for any data type:

uint32_t SomeInteger = 123456UL;
float SomeFloat = 123.456;
uint8_t *bytes;

bytes = (uint8_t*)&SomeInteger;
for (int i = 0; i < sizeof(SomeInteger); i++) Serial.println(bytes[i]);

bytes = (uint8_t*)&SomeFloat;
for (int i = 0; i < sizeof(SomeFloat); i++) Serial.println(bytes[i]);

EDIT: Your conversion from float to integer is done by multiplying the float by 10000 and cast it to an integer (probably unsigned long or uint32_t).

You can convert your given float number (48.15278) into a 4-byte wide array named myData by the following union structure.

union
{
    float x;
    byte myData[4];  //little endian

} data;

data.x = 48.15278;    //equivalent 32-bit binay32 formatted data are:  0x42409C72
1 Like

Thank you, this is exactly what i was looking for !
Is there a way to deal with negative number with two's compliment as easily ?

quentinkb:
Is there a way to deal with negative number with two's compliment as easily ?

The union structure handles well both +ve and -ve numbers. -48.15278 will be transformed into 0xC2409C72. You do the reverse process to retrieve the original float.

Perfect ! Thank you everyone ! This helps me a lot !