将float转换为bigint(又是可移植的方式来获取二进制指数和尾数) [英] Convert float to bigint (aka portable way to get binary exponent & mantissa)
问题描述
在C ++中,我有一个bigint类,可以容纳任意大小的整数.
In C++, I have a bigint class that can hold an integer of arbitrary size.
我想将大浮点数或双精度数转换为bigint. 我有一个可行的方法,但这有点不合常理.我使用IEEE 754数字规范来获取输入数字的二进制符号,尾数和指数.
I'd like to convert large float or double numbers to bigint. I have a working method, but it's a bit of a hack. I used IEEE 754 number specification to get the binary sign, mantissa and exponent of the input number.
这是代码(这里忽略符号,这并不重要):
Here is the code (Sign is ignored here, that's not important):
float input = 77e12;
bigint result;
// extract sign, exponent and mantissa,
// according to IEEE 754 single precision number format
unsigned int *raw = reinterpret_cast<unsigned int *>(&input);
unsigned int sign = *raw >> 31;
unsigned int exponent = (*raw >> 23) & 0xFF;
unsigned int mantissa = *raw & 0x7FFFFF;
// the 24th bit is always 1.
result = mantissa + 0x800000;
// use the binary exponent to shift the result left or right
int shift = (23 - exponent + 127);
if (shift > 0) result >>= shift; else result <<= -shift;
cout << input << " " << result << endl;
它可以工作,但是很丑陋,我不知道它有多便携.有一个更好的方法吗?从浮点数或双精度数中提取二进制尾数和指数的方法是否更丑陋,更便捷?
It works, but it's rather ugly, and I don't know how portable it is. Is there a better way to do this? Is there a less ugly, portable way to extract the binary mantissa and exponent from a float or double?
感谢您的回答.对于后代,这是使用frexp的解决方案.由于存在循环,因此效率较低,但它适用于float和double相似,不使用reinterpret_cast或依赖于任何浮点数表示形式的知识.
Thanks for the answers. For posterity, here is a solution using frexp. It's less efficient because of the loop, but it works for float and double alike, doesn't use reinterpret_cast or depend on any knowledge of floating point number representations.
float input = 77e12;
bigint result;
int exponent;
double fraction = frexp (input, &exponent);
result = 0;
exponent--;
for (; exponent > 0; --exponent)
{
fraction *= 2;
if (fraction >= 1)
{
result += 1;
fraction -= 1;
}
result <<= 1;
}
推荐答案
通常不能使用 查看全文