浮点数转定点数(C++)#
#include <iostream>
int32_t significand, exponent;
以 -1.2
为例,有 \(-1.2 = -0.6 \times 2^1\):
double double_multiplier = -1.2;
获取浮点数的尾数和指数:
double significand_d = std::frexp(double_multiplier, &exponent);
std::cout << significand_d << " " << exponent;
-0.6 1
符合我们的预期。
将双精度尾数转换为整数尾数,即将其转换为小数点位于第 31 位和第 30 位之间的整数。这是通过将双精度值乘以 \(2^{31}\) 然后强制转换为 int
类型来实现的。
significand_d = std::round(significand_d * (1ll << 31));
auto significand_int64 = static_cast<int64_t>(significand_d);
if (significand_int64 == (1ll << 31)) {
significand_int64 /= 2;
++exponent;
}
significand = static_cast<int32_t>(significand_int64);
significand
-1288490189