56 lines
926 B
C
56 lines
926 B
C
#include <assert.h>
|
|
#include <limits.h>
|
|
|
|
/* Access bit-level representation of floating-point number */
|
|
typedef unsigned float_bits;
|
|
|
|
/* Compute (float) i */
|
|
float_bits float_i2f(int i) {
|
|
if (i == INT_MIN) {
|
|
return 0xCF000000U;
|
|
}
|
|
|
|
if (i == 0) {
|
|
return 0;
|
|
}
|
|
|
|
float_bits s = 0, f, e;
|
|
if (i < 0) {
|
|
i = -i;
|
|
s = 0x80000000U;
|
|
}
|
|
|
|
int hb = 30;
|
|
while (!(i >> hb)) {
|
|
hb = hb - 1;
|
|
}
|
|
|
|
i = i ^ (1 << hb);
|
|
e = hb + 127;
|
|
if (hb > 23) {
|
|
f = i >> (hb - 23);
|
|
if ((i & (1 << (hb - 24))) && ((f & 1) || (i & ((1 << (hb - 24)) - 1)))) {
|
|
f = f + 1;
|
|
if (f & 0x00800000U) {
|
|
f = 0;
|
|
e = e + 1;
|
|
}
|
|
}
|
|
} else {
|
|
f = i << (23 - hb);
|
|
}
|
|
|
|
return s | (e << 23) | f;
|
|
}
|
|
|
|
int main() {
|
|
for (int x = INT_MIN; ; x = x + 1) {
|
|
float_bits y = float_i2f(x);
|
|
float *z = (float*) &y;
|
|
assert(*z == (float) x);
|
|
|
|
if (x == INT_MAX) {
|
|
break;
|
|
}
|
|
}
|
|
} |