简体   繁体   中英

C++ int or float to char array

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM