Question

How can I return only the exponent part of a floating point number? It's single precision so I need to get the value of the eight exponent bits.

int floatExp(float f) { 
 //Return the exponent value for f. return tmax if f is nan or infinity
}

No correct solution

OTHER TIPS

The standard way to extract the binary exponent is to use the frexp() function from math.h. See http://www.csse.uwa.edu.au/programming/ansic-library.html#float

If you need the decimal exponent, use the log10() function in math.h.

Code certainly should pass a float rather than unsigned.

// int floatExp(unsigned f)
int floatExp(float f)

Use isfinite and frexpf().

#include <math.h>
int floatExp2(float value) {
  int exp;
  if (isfinite(value)) {
    frexpf(&exp);
    return exp;
  }
  return tmax;
}

For base 10, a bit more work.

#include <math.h>
int floatExp10_(float value) {
  if (isfinite(value)) {
    if (value == 0.0) return 0;
    float exp = log10f(fabsf(value));

    // use floorf() rather than `(int) exp`.  
    // This does the proper rounding when `exp` is + or -
    return (int) floorf(exp);
  }
  return tmax;
}

C does not define that floating point nor float have "eight exponent bits". It also does not define that the exponent is a binary one. Many implementations use IEEE 754 single-precision binary floating-point format: binary32 which does have an 8-bit power-of-2 biased exponent.

A hack way is to use a union. This non-portable method is highly dependent on knowing the floating point format, size of the integer, the endian-ness of the float and integer. The following, or a variation, of it may work in OP's environment.

int floatExp_hack(float value) {
  if (isfinite(value)) {
    union {
      float f;
      value unsigned long ul;
    } u;
    assert(sizeof u.f == sizeof u.ul);
    u.f = value;
    return (u.ul >> 23) & 0xFF;
  }
  return tmax;
}

Take a log in whatever base you're interested in getting an exponent in.

Hacking around with bits is only going to work if your platform uses IEEE floats, which isn't guaranteed. Wikipedia's article on single precision IEEE floating points will show you what bits to mask, but note that some exponents have special values.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top