简体   繁体   English

将double转换为long double的算法

[英]Algorithm to convert double to long double

If double is a 64 bit IEEE-754 type and long double is either an 80 or 128 bit IEEE-754 type, what is the algorithm that is used by the hardware (or the compiler?) in order to perform the conversion: 如果double是64位IEEE-754类型,而long double是80或128位IEEE-754类型,则硬件(或编译器)使用什么算法执行转换:

double d = 3.14159;
long double ld = (long double) d;

Also, it would be amazing if someone could list a source for the algorithm, as I've had no luck finding one thus far. 另外,如果有人可以列出该算法的来源,那将是惊人的,因为到目前为止我还没有运气。

For normal numbers like 3.14159, the procedure is as follows: 对于3.14159之类的常规数字,过程如下:

separate the number into sign, biased exponent, and significand
add the difference in the exponent biases for long double and double
    (0x3fff - 0x3ff) to the exponent.
assemble the sign, new exponent, and significand (remembering to make the
    leading bit explicit in the Intel 80-bit format).

In practice, on common hardware with the Intel 80-bit format, the “conversion” is just a load instruction to the x87 stack (FLD). 实际上,在具有Intel 80位格式的通用硬件上,“转换”只是x87堆栈(FLD)的加载指令。 One rarely needs to muck around with the actual representation details, unless targeting a platform without hardware support. 除非针对没有硬件支持的平台,否则很少需要弄乱实际的表示细节。

It's defined in the C Standard - google for N1570 to find a copy of the latest free draft. 它在C标准-Google for N1570中定义,以查找最新的免费草稿的副本。 Since all "double" values can be represented in "long double", the result is a long double with the same value. 由于所有“ double”值都可以用“ long double”表示,因此结果是具有相同值的long double。 I don't think you will find a precise description of the algorithm that the hardware uses, but it's quite straightforward and obvious if you look at the data formats: 我认为您不会找到硬件使用的算法的精确描述,但是如果您查看数据格式,这将非常简单明了:

Examine the exponent and mantissa bits to find if the number is Infinity, NaN, a normalized number, a denormalised number or a zero, produce a long double Infinity or NaN when needed, adjust the exponent of normalized numbers and shift the mantissa bits into the right place, adding an implicit highest mantissa bit, convert denormalised numbers to normalised numbers, and zeroes to long double zeroes. 检查指数和尾数位以发现数字是Infinity,NaN,归一化数,非归一化数还是零,在需要时产生长双倍Infinity或NaN,调整归一化数的指数并将尾数位移到正确的地方,添加一个隐式的最高尾数位,将非规范化数字转换为规范化数字,并将零转换为长双零。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM