get_exponent

=Getting the exponent of a float=

code format="c"
 * 1) define FLOAT_EXP_MASK 0x7F800000

int get_exponent(float f) { int value, *fakeint = (int *) &f; value = *fakeint & FLOAT_EXP_MASK) >> 23;   return value - 127; } code

You should be able to understand every part of the above function. It's kind of dense, here's the important stuff:
 * 1) We have a bitmask (FLOAT_EXP_MASK) defined at the beginning so we don't have to use a literal each time. This is just for code clarity.
 * 2) We set an integer pointer to the address of the floating point number passed in:
 * 3) We get the address of f (with "&f")
 * 4) We cast it to an integer pointer (with "(int *)")
 * 5) We assign it to the integer pointer
 * 6) We have to do this because we want to use bitwise operators, which aren't valid except on integer types (char, short, int, long, etc.)
 * 7) We mask //away// everything that's not part of the exponent (use "&" with a 0 bit in those positions)
 * 8) We right shift 23 bits (the length of the mantissa) to make our number aligned properly
 * 9) We subtract 127 to deal with the offset.

Note that this could all be done at once, but it would be kind of ugly:

code format="c" int get_exponent(float f) { return (*(int *)&f >> 23 & 0xFF) - 127; } code

Note that above we applied the mask after the bitshift, and that we left out unnecessary parenthesis, relying on order-of-operations. The later is not a good habit. Functions like the one above are okay in small doses, but use comments to explain them.