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
.
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.
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();
}
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
*/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With