Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative to memcpy

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

like image 748
Michael Knudsen Avatar asked Dec 18 '25 04:12

Michael Knudsen


2 Answers

You could just read directly into the buffer

float data[9];
udp.read((char*)data, sizeof(data));
like image 140
cup Avatar answered Dec 20 '25 21:12

cup


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]);
like image 31
Jiminion Avatar answered Dec 20 '25 22:12

Jiminion



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!