将原始二进制转换为浮点数0以获取较小值

时间:2015-02-13 21:07:44

标签: floating-point intel floating-point-precision floating-point-conversion

我试图读取2个32位值(假设它们是ieee 745单精度浮点值)并比较它们以使用以下片段检查它们是否相等,

#include <stdio.h>
#include <stdint.h>

void main(){
    int a;
    int b;
    //a = 0x3f99999a ;
    //b = 0x3fa66666 ;
    a = 0xfa98 ;
    b = 0x65cc ;
    printf("Comparison is %d\n",((*(float*)&(a))==(*(float*)&(b))));
    printf("Numbers are a= %f and b = %f \n",(*(float*)&(a)),(*(float*)&(b)));
}

以下片段在两个不同的平台上运行,两者都给出了不同的结果(一个是正确的,另一个是错误的)。没有编译器优化。

平台A - Xeon服务器(Intel(R)Xeon(R)CPU E5),带有fedora版本20和gcc编译器版本(4.8.3(Red Hat 4.8.3-7))

a = 0xfa98且b = 0x65cc的输出为:

Comparison is 1       // This is clearly wrong as both numbers are unequal
Numbers are a= 0 and b = 0 // Casting it to float is causing them to 0 ??

a = 0x3f99999a和b = 0x3fa66666的输出是:

Comparison is 0 // This is correct
Numbers are a= 1.2 and b = 1.3 // True decimal values for given 745 representation

平台B - 带有ubuntu 14.04和gcc编译器版本(4.8.2(Ubuntu 4.8.2-19 ubuntu1))的Intel i7(Intel(R)i7-3770)

a = 0xfa98且b = 0x65cc的输出为:

Comparison is 0       // This is correct !!
Numbers are a= 0 and b = 0 // Still  0 because numbers are subnormal

a = 0x3f99999a和b = 0x3fa66666的输出是:

Comparison is 0 // This is correct
Numbers are a= 1.2 and b = 1.3 // True decimal values for given 745 representation

所以我的问题是平台A为浮动比较产生错误结果的原因。第一组值是次正规的,十进制表示非常小但绝对不相等。其中代码适用于第二组值(大值)。有人可以解释我这个。为什么平台A没有显示平台B那样的值不相同?

1 个答案:

答案 0 :(得分:0)

问题是mxcsr寄存器的DAZ位。一台机器A设置它所以它将非正规数视为0。在机器2 DAZ被重置的情况下,因此它将其归一化并将非正规值视为不同的值,这导致比较结果不相等。但我非常感谢所有帮助人:)!没有你的帮助就无法调试它。