如何将一个float变量赋给一个unsigned int变量,位图,而不是转换 [英] How can I assign a float variable to an unsigned int variable, bit image, not cast
本文介绍了如何将一个float变量赋给一个unsigned int变量,位图,而不是转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道这是一个奇怪的事情,它不可移植。但我有一个分配的unsigned int数组,偶尔我想存储一个浮点数。我不想转换float或将其转换为最接近的等价int;我想把浮点的精确位图存储在unsigned int的分配空间中,这样我可以稍后将它作为一个浮点检索,并保留其原来的浮点值。
解决方案
这可以通过一个简单的副本实现:
uint32_t dst;
float src = get_float();
char * const p = reinterpret_cast< char *>(& dst);
std :: copy(p,p + sizeof(float),reinterpret_cast< char *>(& src));
//现在读取dst
>
I know this is a bizarre thing to do, and it's not portable. But I have an allocated array of unsigned ints, and I occasionaly want to "store" a float in it. I don't want to cast the float or convert it to the closest equivalent int; I want to store the exact bit image of the float in the allocated space of the unsigned int, such that I could later retrieve it as a float and it would retain its original float value.
解决方案
This can be achieved through a simple copy:
uint32_t dst;
float src = get_float();
char * const p = reinterpret_cast<char*>(&dst);
std::copy(p, p + sizeof(float), reinterpret_cast<char *>(&src));
// now read dst
Copying backwards works similarly.
这篇关于如何将一个float变量赋给一个unsigned int变量,位图,而不是转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文