沒有必要使用浮點數編碼。 C提供了以便攜方式處理浮點值的例程。以下作品。
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
/* This should be replaced with proper allocation for the floating-point
type.
*/
int powers[53];
double x = atof(argv[1]);
if (x <= 0)
{
fprintf(stderr, "Error, input must be positive.\n");
return 1;
}
// Find value of highest bit.
int e;
double f = frexp(x, &e) - .5;
powers[0] = --e;
int p = 1;
// Find remaining bits.
for (; 0 != f; --e)
{
printf("e = %d, f = %g.\n", e, f);
if (.5 <= f)
{
powers[p++] = e;
f -= .5;
}
f *= 2;
}
// Display.
printf("%.19g =", x);
for (int i = 0; i < p; ++i)
printf(" + 2**%d", powers[i]);
printf(".\n");
// Test.
double y = 0;
for (int i = 0; i < p; ++i)
y += ldexp(1, powers[i]);
if (x == y)
printf("Reconstructed number equals original.\n");
else
printf("Reconstructed number is %.19g, but original is %.19g.\n", y, x);
return 0;
}
由於該標準不能保證IEEE浮點,因此這種方法不太可能是可移植的。另外,如果「ones」數字超出範圍呢? – Mysticial 2012-08-03 21:40:09
實際上,我不介意非可移植性,只要它可以工作,比如Linux x86_64,帶有gcc和有保證的IEEE浮點。任何其他體系結構都可以使用微調代碼或慢天真的方法。 – Vortico 2012-08-03 21:43:04
避免低級別,按位操作的要點是什麼? – Nino 2012-08-03 21:43:30