从C++中的符号、指数和尾数部分创建 NaN 浮点值
Creating a NaN float value from the sign, exponent and mantissa parts in C++
我需要在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";
}
相关文章:
- 在将 new 与指针一起使用时,创建数组的指定长度
- 在函数中使用 const int size 参数创建数组会在 Visual Studio 中抛出错误 C++:表达式的计
- 合并排序不排序自创建数组类 c++
- 基于参数创建数组
- 使用new创建数组而不声明大小
- c++用输入数据创建数组
- 从类 c++ 动态创建数组
- 如何使用 void 函数从类创建数组
- 未知大小的数组作为类成员,用于在运行时(对象创建时间)创建数组的对象
- 如何在不知道Arduino中知道其大小的情况下创建数组和存储值
- 使用动态分配创建数组并将元素插入其中
- 是否可以使用C 函数中的const int参数创建数组
- 如何在C++函数中创建数组
- 使用 ::std::vector 创建数组
- 在编译时以增量方式创建数组
- Numpy C API - 使用 PyArray_Descr 创建数组会导致段错误
- 为什么当我尝试在类中创建数组时"invalid use of non-static data member"我会收到错误?
- 取消引用指针以创建数组的副本
- C++ 在堆上创建数组而不对其进行初始化
- 数组的维度是在创建数组的那一刻确定的,以后不能更改的,这是真的吗?