0

I am working on a project in my Arduino, where I want to send several values to a destination through a very slow radio link.

I need to send 7 long variables, that are 4 bytes each. So rather than converting them to hex strings for up to 64 bytes of data, I would love to store them all in an array, char payload[32];

I tried doing something like this:

long first = 5000;
long second = 10000;
char payload[8];
long* pointer;

pointer = &payload[0];
*pointer = first;
pointer = &payload[4];
*pointer = second;

But I get hit by a conversion error.

What is the proper way of doing this?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
metichi
  • 183
  • 7

1 Answers1

3

A char* is not compatible with a long*, so you need an explicit type-cast when assigning your pointer variable, eg:

long first = 5000;
long second = 10000;
char payload[sizeof(long)*2];
long* pointer;

pointer = reinterpret_cast<long*>(&payload[0]);
*pointer = first;
pointer = reinterpret_cast<long*>(&payload[4]);
*pointer = second;

Alternatively (and safer), use memcpy() instead, eg:

long first = 5000;
long second = 10000;
char payload[sizeof(long)*2];

memcpy(&payload[0], &first, sizeof(first));
memcpy(&payload[4], &second, sizeof(second));

That being said, if you want to ensure a 32-bit integer is used for transmission, you really should use int32_t instead of long. long is not 32-bit on all platforms, though it is on Arduino (who is to say that can never change in the future, though). You should always use fixed-width types when you need to use specific bit sizes.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • 1
    Less and less important these days, but also keep an eye out for [endian](https://en.wikipedia.org/wiki/Endianness) differences between the source and destination. [`ntohl` and `htonl`](https://stackoverflow.com/questions/36924598/understanding-htonl-and-ntohl) may come in handy. – user4581301 Jul 28 '20 at 18:33