简体   繁体   English

如何在 C 的 uint64_t 变量中存储浮点值?

[英]How to store float value in uint64_t variable in C?

I have an array of uint64_t values uint64_t *data;我有一组uint64_tuint64_t *data; in where I need to store 4 different data types: int , char* , bool , float .在我需要存储 4 种不同数据类型的地方: intchar*boolfloat I solved every type by simple casting to (uint64_t) , but it doesn`t work for float:我通过简单转换为(uint64_t)解决了每种类型,但它不适用于 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 .我尝试以各种方式组合转换,但结果是0.01.0

... to store float value in uint64_t variable... ...将float值存储在uint64_t变量中...

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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