Question

I'm trying to convert a integer or a float to a char array, in a specific form (programming for mbed, a micro-controller).

The integers should be 32-bit big-endian two's complement integer The floats should be 32-bit big-endian IEEE 754 floating point number

Tried a few things:

uint8_t *v;
uint8_t valuePos = 3;
v = (uint8_t *)datum->data.i; //I get the int or float from datum->data.i
buff[lengthEnd++] = v[valuePos--]; //buff is the char array
buff[lengthEnd++] = v[valuePos--];
buff[lengthEnd++] = v[valuePos--];
buff[lengthEnd++] = v[valuePos]; 

and

uint32_t i = BigEndian(datum->data.i);
uint8_t * ptr = (uint8_t *) &i;
strcat(buff, (char *) ptr); //maybe strcat isn't a good function to use here
lengthEnd += 4;

But I can't make it work, I always get some other number. What is going wrong?

Was it helpful?

Solution

It looks like you missed & operator.
Please try this:

v=(uint8_t *)&datum->data.i;

And never use strcat for binary data. It's for strings. Binary data should be handled with something like memcpy.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top