11

I'm trying to get the mantissa of a float (just to learn), but it isn't working as expected.

structure of a floating point number

The mantissa of say 5.3 is 53, right? I tried this code:

System.out.println(Float.floatToIntBits(5.3f) & 0x7FFFFF);

It printed 2726298. Shouldn't it remove the exponent bits and leave 53? I tried plenty of things, but this always happens. What am I doing wrong here?

user3452725
  • 603
  • 1
  • 6
  • 14

2 Answers2

15

The formula for single precision following the IEEE standard is:

(-1)^sign + 1.Mantissa x 2^(Exponent - Bias)

So 5.3 base 10 is 101.0100110011001100110011 base 2

101.0100110011001100110011 = 1.010100110011001100110011 * 2^2

2^2 = 2^(exp - bias) having bias = 127 (according to the IEEE standard for single precision)
so: exp - 127 = 2 => exp = 129 base 10 or 10000001 base 2

Single precision table:

0 | 10000001 | 01010011001100110011001

Sign = 0
Exp = 129
Mantissa = 2726297

CMPS
  • 7,733
  • 4
  • 28
  • 53
  • Hmmm... Seems I'm interpreting something wrong then. `Integer.toBinaryString(Float.floatToIntBits(5.3f))` prints `1000000101010011001100110011010`, and it doesn't look like the exponent there matches... Where am I going wrong? – awksp Jun 17 '14 at 22:13
  • How is the bias determined? If it's defined by IEEE and Java is IEEE-compliant shouldn't that not be an issue? – awksp Jun 17 '14 at 22:23
  • @user3580294 bias is determined by the IEEE standard, for single precision (float) it is 127 and for double precision it is 1023 – CMPS Jun 17 '14 at 22:29
  • @user3580294 yes, I accidentally flipped the position of Exp and Bias in the formula – CMPS Jun 17 '14 at 22:31
1

From the article IBM: Java's new math. Floating-point numbers (in Russian) the simplest way to get the mantissa is:

public static double getMantissa(double x) {
    int exponent = Math.getExponent(x);
    return x / Math.pow(2, exponent);
}
Sergey Ponomarev
  • 2,947
  • 1
  • 33
  • 43