문제

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

도움이 되었습니까?

해결책 2

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]);

다른 팁

You could just read directly into the buffer

float data[9];
udp.read((char*)data, sizeof(data));

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top