Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Double to Binary representation?

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.

like image 542
Besnik Avatar asked Jun 15 '11 15:06

Besnik


People also ask

How do you convert a double number to binary?

An easy method of converting a decimal number into binary number is by dividing the decimal number by 2 progressively, until the quotient of zero is obtained. The binary number is obtained by taking the remainder after each division in the reverse order.


2 Answers

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();
}
like image 135
Bax Avatar answered Oct 04 '22 06:10

Bax


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
*/
like image 24
Matt Ball Avatar answered Oct 04 '22 07:10

Matt Ball