Skip to content

Instantly share code, notes, and snippets.

@Ethkuil
Last active October 17, 2024 14:34
Show Gist options
  • Save Ethkuil/72ecb268f302e1300e5c866f989a60da to your computer and use it in GitHub Desktop.
Save Ethkuil/72ecb268f302e1300e5c866f989a60da to your computer and use it in GitHub Desktop.
/*
* float_i2f - Return bit-level equivalent of expression (float) x
* Result is returned as unsigned int, but
* it is to be interpreted as the bit-level representation of a
* single-precision floating point values.
* Legal ops: Any integer/unsigned operations incl. ||, &&. also if, while
* Max ops: 30
* Rating: 4
*/
unsigned float_i2f(int x) {
unsigned sign, exp, frac;
unsigned E, x_copy;
unsigned round_num_digits, round_part, round_mid;
// special cases
if (x == 0) return 0;
if (x == 0x80000000) return 0xcf000000;
// sign
sign = x & 0x80000000;
if (sign) x = -x;
// exp
// E = ilog2(x);
E = 0;
for (x_copy = x; x_copy >>= 1;) ++E;
exp = E + 127;
// frac
// clear the leading 1
frac = x & ((1 << E) - 1);
if (E <= 23) {
frac <<= 23 - E;
} else {
round_num_digits = E - 23;
round_part = frac & ((1 << round_num_digits) - 1);
frac >>= round_num_digits;
// round
round_mid = 1 << (round_num_digits - 1);
if (round_part > round_mid || (round_part == round_mid && (frac & 1) /* round to even */)) {
++frac;
// frac may have a carry.
}
}
return sign | ((exp << 23) + frac);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment