简体   繁体   中英

How to store float value in uint64_t variable in C?

I have an array of uint64_t values uint64_t *data; in where I need to store 4 different data types: int , char* , bool , float . I solved every type by simple casting to (uint64_t) , but it doesn`t work for float:

float val = 1.5f;
uint64_t var = (uint64_t) val;
printf("%.1f", (float) var); // prints 1.0

Is there a way to move data between variables on even lower level than casts? I've tried to combine casts in every way but the result was 0.0 or 1.0 .

... to store float value in uint64_t variable...

Copy it.

float var_f = 1.5f;
uint64_t var_u64;
_Static_assert(sizeof var_f <= sizeof var_u64, "Wide float");
memcpy(&var_u64, &var_f, sizeof var_f);

To recover

memcpy(&var_f, &var_u64, sizeof var_f);
printf("%g\n", var_f);

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