Convert Double to Binary representation?

后端 未结 6 1618
深忆病人
深忆病人 2020-11-28 16:04

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 nu

6条回答
  •  广开言路
    2020-11-28 16:19

    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.

提交回复
热议问题