#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 & 0x80000000U, f = uf & 0x007FFFFF, e = (uf >> 23) & 0xFF; if (e == 0xFFU) { return uf; } if (e > 1) { e = e - 1; return s | (e << 23) | f; } if (e == 1) { f = f | (1 << 23); e = 0; } int t = f; f = f >> 1; if (t & f & 1) { f = f + 1; } return s | (e << 23) | f; } int main() { for (float_bits x = 0; ; x = x + 1) { 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; } } }