Double to base 2 conversion (is there a simple way?)

1.2k Views Asked by At

Hi and thanks for helping,

(Working with Java) I've looked around a bit for converting a Double to base 2 (still in double) but I could not find a simple way. I read that given how Doubles were coded the methods like Double.doubleToRawLongBits() can give Base 2 but with a different interpretation.

For converting int it pretty simple with the method: Integer.toString(x, 2)

I was wondering if someone knew a simple way to convert a Double to it's base 2 correspondant as a Double? If I have a Double = 0.25 after the conversion I would like to see a double = 0.01.

Thanks

2

There are 2 best solutions below

0
On

You can extract the part of a double like this.

long val = Double.doubleToRawLongBits(d);
int sign = (int) (val >>> 63);
int exp = (int) ((val >>> 52) & 2047);
long mantissa = val & ((1L << 52) - 1);

After that you can print the mantissa with Long.toString(mantissa, 2) and the exponent and sign however you like. This assumes normal numbers.

0
On

A cross-platform solution that doesn't rely on binary representation of double:

String result = "";
if (x < 0) { result = "-"; x = -x; }
result += Integer.toString((int)x, 2);
double frac = x - (int)x;
int digits = 0;
while (frac > 0 && digits < MAX_DIGITS) {
  if (digits == 0) result += ".";
  frac *= 2; // now 0 < frac < 2
  result += Integer.toString((int)frac, 2); // it's 0 or 1
  frac = frac - (int)frac;
  digits++;
}