Reputation: 629
I am using an Arduino to parse UDP packages sent from an application on my local network. The messages contain 36 bytes of information. The first four bytes represent one (single-precision) float, the next four bytes another one, etc.
The Arduino function udp.read() reads the data as chars, and I end up with an array
char data[36] = { ... };
I am now looking for a way to convert this into the corresponding nine floats. The only solution I have found is repeated use of this trick:
float f;
char b[] = {data[0], data[1], data[2], data[3]};
memcpy(&f, &b, sizeof(f));
However, I am sure there must be a better way. Instead of copying chunks of memory, can I get away with using only pointers and somehow just tell C to interpret b as a float?
Thanks
Upvotes: 3
Views: 5896
Reputation: 8267
You could just read directly into the buffer
float data[9];
udp.read((char*)data, sizeof(data));
Upvotes: 5
Reputation: 182674
This is dangerous and technically not well defined, and the way you are doing it is better.
That said, on some platforms you can get away with:
float *f1 = (float *)data;
float *f2 = (float *)(data + 4);
Also, in your code I see no reason why you don't memcpy
directly from data + offset
.
Upvotes: 3
Reputation: 5164
union Data
{
char data[36];
float f[9];
};
union Data data;
data.data[0] = 0;
data.data[1] = 0;
data.data[2] = 0;
data.data[3] = 0;
fprintf(stdout,"float is %f\n",data.float[0]);
Upvotes: 3