#include #include #include /* Access bit-level representation of floating-point number */ typedef unsigned float_bits; /* computs 0.5*f. If f is NaN, then return f. */ float_bits float_half(float_bits uf) { float_bits s = uf & 0x80000000, f = uf & 0x007FFFFF, e = (uf >> 23) & 0xFF; if (e == 0xFF) { return uf; } if (e > 1) { e--; return s | (e << 23) | f; } if (e == 1) { f |= 1 << 23; e = 0; } int t = f; f >>= 1; if (t & f & 1) { f++; } return s | (e << 23) | f; } int main() { for (float_bits x = 0; ; x++) { float *a = (float*) &x; float b = 0.5 * *a; float_bits c = float_half(x); float *d = (float*) &c; assert(b == *d || (isnan(b) && isnan(*d))); if (x == UINT_MAX) { break; } } }