保留顺序时将浮点转换为unsigned int [英] Converting floating point to unsigned int while preserving order
问题描述
我发现了很多关于SO的答案,重点是将 float
转换为 int
.
I have found a lot of answers on SO focusing on converting float
to int
.
我只处理正浮点值.我一直在使用的一种简单方法是:
I am manipulating only positive floating point values. One simple method I have been using is this:
unsigned int float2ui(float arg0) {
float f = arg0;
unsigned int r = *(unsigned int*)&f;
return r;
}
上面的代码运行良好,但是无法保留数字顺序.按顺序,我的意思是这样:
The above code works well yet it fails to preserve the numeric order. By order I mean this:
float f1 ...;
float f2 ...;
assert( ( (f1 >= f2) && (float2ui(f1) >= float2ui(f2)) ) ||
( (f1 < f2) && (float2ui(f1) < vfloat2ui(f2)) ));
我尝试使用具有相同结果的联合.任何想法?我使用Homebrew gcc 5.3.0.
I have tried to use unions with the same results. Any idea? I use Homebrew gcc 5.3.0.
推荐答案
您所编写的代码具有未定义的行为.如果您想半移植地访问 float
的表示形式(实现定义,定义良好并假定IEEE 754,并且float和integer字节序匹配),则应该执行以下操作:
The code you're using, as writen, has undefind behavior. If you want to access the representation of float
s semi-portably (implementation-defined, well-defined assuming IEEE 754 and that float and integer endianness match), you should do:
uint32_t float2ui(float f){
uint32_t r;
memcpy(&r, &f, sizeof r);
return r;
}
对于非负值,浮点值和表示形式之间的映射保留顺序.如果您认为自己无法保留订单,则需要准确查看您认为哪些值是反例.
For non-negative values, this mapping between floating point values and representation is order-preserving. If you think you're seeing it fail to preserve order, we'll need to see exactly what values you think are a counterexample.
这篇关于保留顺序时将浮点转换为unsigned int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!