Convert Double to Binary representation?

2020-01-25 11:16发布

问题:

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.

回答1:

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
*/


回答2:

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();
}


回答3:

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) );


回答4:

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



回答5:

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