Convert Double to Binary representation?
Asked Answered
C

8

13

I tried to convert a double to its binary representation, but using this Long.toBinaryString(Double.doubleToRawLongBits(d)) doesn't help, since I have large numbers, that Long can't store them i.e 2^900.

Celsacelsius answered 15/6, 2011 at 15:1 Comment(4)
The binary representation can only be 64-bit long as a double is 64-bit. I don't know where 2^900 comes from.Fusspot
Just out of curiosity, what kind of application do you work on to need to work with such a large number ?Especially
Useful link : #398192Immobility
I have to do some experiments thought to do sampling on those possibilities but I see i need to do random sampling!Celsacelsius
S
30

Long.toBinaryString(Double.doubleToRawLongBits(d)) appears to work just fine.

System.out.println("0:                0b" + Long.toBinaryString(Double.doubleToRawLongBits(0D)));
System.out.println("1:                0b" + Long.toBinaryString(Double.doubleToRawLongBits(1D)));
System.out.println("2:                0b" + Long.toBinaryString(Double.doubleToRawLongBits(2D)));
System.out.println("2^900:            0b" + Long.toBinaryString(Double.doubleToRawLongBits(Math.pow(2, 900))));
System.out.println("Double.MAX_VALUE: 0b" + Long.toBinaryString(Double.doubleToRawLongBits(Double.MAX_VALUE)));

/*
    prints:
    0:                0b0
    1:                0b11111111110000000000000000000000000000000000000000000000000000
    2:                0b100000000000000000000000000000000000000000000000000000000000000
    2^900:            0b111100000110000000000000000000000000000000000000000000000000000
    Double.MAX_VALUE: 0b111111111101111111111111111111111111111111111111111111111111111
*/
Slipslop answered 15/6, 2011 at 15:6 Comment(1)
Where are the missing 63rd and 64th bits?Mechanotherapy
A
8

You may want to process whole and fractional part :

public String toBinary(double d, int precision) {
    long wholePart = (long) d;
    return wholeToBinary(wholePart) + '.' + fractionalToBinary(d - wholePart, precision);
}

private String wholeToBinary(long l) {
    return Long.toBinaryString(l);
}

private String fractionalToBinary(double num, int precision) {
    StringBuilder binary = new StringBuilder();
    while (num > 0 && binary.length() < precision) {
        double r = num * 2;
        if (r >= 1) {
            binary.append(1);
            num = r - 1;
        } else {
            binary.append(0);
            num = r;
        }
    }
    return binary.toString();
}
Aggrieve answered 10/8, 2015 at 19:59 Comment(0)
T
1

Here is a small snippet which converts the fractional part of the double to binary format:

String convertToBinary(double number) {
    int i=1;
    String num="0.";
    double temp,noofbits=32;
    while (i<=noofbits && number>0) {
        number=number*2;
        temp=Math.floor(number);
        num+=(int)temp;
        number=number-temp;
        i++;
    }

where noofbits gives the bitsize you want the fractional part to be limited to. For the whole number part directly use the Integer.toBinaryString() along with the floor value of the double and append to the fractional binary string.

Tilford answered 5/5, 2020 at 15:15 Comment(0)
R
0

Have you tried using java.math.BigInteger and calling toString(int radix) with a parameter of 2?

Retrieval answered 15/6, 2011 at 15:4 Comment(5)
Double.doubleToRawLongBits(d) is only ever going to return a 64-bit long.Fusspot
By the way, the above applies to integer numbers only -- which I have assumed to be the case based on the 2^900 you mentioned?Retrieval
The thing is that i compute that using the Math.pow(2, 900) which returns double!Celsacelsius
Yup agree :) Thanks for the help all!Celsacelsius
@Peter : LOL ! I do repeat, "all double are 64-bit, all double are 64-bit" ... :-)Immobility
L
0

You can use a BigInteger to hold your large number and the BigInteger.toString() method to retrieve a binary representation of it.

BigInteger bigNum = new BigInteger(sYourNum);
System.out.println( bigNum.toString(2) );
Leucocytosis answered 15/6, 2011 at 15:6 Comment(1)
this does not convert the fractional part of a doubleSubstage
C
0

Though this question is old, and good answers are present.

I just come up with an idea that you can write the double value to a file/memory region through DataOutputStream and read it as bytes.

Therefore we can use ByteArrayOutputStream to hold the binary representation and fetch the bytes directly to avoid I/O operations on disk. (javadoc, also this post)

The scala version of it looks like:

import java.io._

val baos = new ByteArrayOutputStream(8)
val dos = new DataOutputStream(baos)
dos.writeDouble(1.23)
dos.close()

// this 'Array[Byte]' or 'byte[]' in java holds the correct binary representation (big-endian) of the double. 
val binaryRepresentation = baos.toByteArray() 
baos.close()

Certes answered 9/3, 2022 at 7:44 Comment(0)
M
0

What I use:

private static final String ZEROS = "0000000000000000000000000000000000000000000000000000000000000000";

public String double2string(Double d) {
    String binary = Long.toBinaryString(Double.doubleToRawLongBits(d));
    return ZEROS.substring(binary.length()) + binary;
}

/*
0.0 => 0000000000000000000000000000000000000000000000000000000000000000
1.0 => 0011111111110000000000000000000000000000000000000000000000000000
2.0 => 0100000000000000000000000000000000000000000000000000000000000000
3.0 => 0100000000001000000000000000000000000000000000000000000000000000
4.0 => 0100000000010000000000000000000000000000000000000000000000000000
5.0 => 0100000000010100000000000000000000000000000000000000000000000000
*/

A good place to understand these values is https://en.wikipedia.org/wiki/Double-precision_floating-point_format, and they are useful for

  • understanding floating point representation
  • writing unit tests that check doubles with total precision

Reminder: integers between -(253-1) and 253-1 have an exact representation as doubles.

Mikkanen answered 18/2, 2024 at 18:26 Comment(0)
S
-1

You can use Double.toHexString(d) and then transform the hexadecimal string into a binary one using a for loop and a StringBuilder.

Spinoza answered 15/6, 2011 at 15:8 Comment(1)
Thanks this might help on my problem!Celsacelsius

© 2022 - 2025 — McMap. All rights reserved.