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.
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.
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.
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()