从C++中的符号、指数和尾数部分创建 NaN 浮点值

Creating a NaN float value from the sign, exponent and mantissa parts in C++

本文关键字:创建 数部 NaN C++ 符号 指数      更新时间:2023-10-16

我需要在C++中创建一个具有 NaN 值的浮点变量。我还需要能够看到哪个 NaN 具有更大的值。要比较 NaN,您需要查看浮标的尾数部分。使用标准创建 NaN

nanf("abc"); 

方法导致 NaN 具有相同的尾数,即使在 nanf 函数中使用不同的字符串也是如此。通过从位模式的基本部分创建NaN应该证明提供不同的尾数,因此可以对尾数的大小进行简单的排序。

看看frexp()函数族以及ldexp(),这与frexp()相反

链接: http://www.cplusplus.com/reference/cmath/ldexp/

下面是

具有联合和整数位字段的类型双关浮点值的示例。

#include <iostream>
union floatPun {
    struct {
        unsigned int mantissa : 23;
        unsigned int exponent : 8;
        unsigned int sign     : 1;
    };
    float value;
};
union doublePun {
    struct {
        unsigned long long mantissa : 52;
        unsigned long long exponent : 11;
        unsigned long long sign     : 1;
    };
    float value;
};
template <typename PunT>
static int compare_mantissas(const PunT& a, const PunT& b) {
    return int(a.mantissa > b.mantissa) - (b.mantissa > a.mantissa);
}
int main() {
    floatPun fa = {0}, fb = {0};
    // make NaNs
    fa.exponent = fb.exponent = 0xff;
    fa.mantissa = 1;
    fb.mantissa = 2;
    std::cout << "fa: " << fa.value << "   fb: " << fb.value << "n";
    // compare mantissas
    static const char* const cmp_labels[] = {"less than", "equal to", "greater than"}; 
    std::cout << "mantissa of fa is " 
        << cmp_labels[1 + compare_mantissas(fa, fb)]
        << " mantissa of fbn";
    // change fa to +infinity
    fa.mantissa = 0;
    std::cout << "changed fa's mantissa to zero: " << fa.value << "n";
}