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
.
CodePudding user response:
... to store
float
value inuint64_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);