-3

Is there a way to convert double to binary in java please can you explain with an example i want the output to be like double 2.1 = binary 10.1

Mad max
  • 99
  • 2
  • 10
  • 2
    What exactly are you trying to achieve? Are you aware of what binary numbers are? `10.1` for sure isn't one. – Thomas Jul 27 '21 at 05:55
  • @user16320675 I stand corrected, you're right. In terms of software I normally don't think of binary as anything other than "integer" representations and I'm not sure the OP doesn't have the same thought in mind. – Thomas Jul 27 '21 at 06:12
  • @Thomas thank you guys ill try the below code I just got confused i know IEEE but I'm having a hard time trying to write a program for that my intention is to let user input a 2 binary numbers and let them chose whatever the opera they want and give them the calculated answers I already made that with integer but I wanna let users input doubles too – Mad max Jul 27 '21 at 07:55
  • "I already made that with integer but I wanna let users input doubles too" - do you mean "integer" binary numbers and now you want to support fractions as well? What is the goal of this? Just a learning exercise or should the users actually get some value out of that? There might be practical reasons for a "fractional binary calculator" but I can't think of one atm. – Thomas Jul 27 '21 at 09:03
  • @Thomas Yeah im making this for a project and i wanted to learn about the fraction part too – Mad max Jul 27 '21 at 09:38
  • @Thomas hey found a method i think it will work if you are interested heres the link https://www.codespeedy.com/convert-decimal-fraction-to-binary-in-java/ it works bro thanks for the support – Mad max Jul 27 '21 at 09:42

3 Answers3

2

Use Double.doubleToRawLongBits(double), and then Long.toBinaryString(long) on the result:

double d = 0.4;
System.out.println(Long.toBinaryString(Double.doubleToRawLongBits(d)));

Source

HiEd
  • 160
  • 3
1

You can use Long.toBinaryString(Double.doubleToRawLongBits(d))

public class Example{

    public static void main(String[] args) {
        double d = 10.1; 
        String l = Long.toBinaryString(Double.doubleToRawLongBits(d));
        System.out.println(l);
    }
}

Output will look like this

100000000100100001100110011001100110011001100110011001100110011
1

Your idea of how doubles work / are stored is not quite right. I found this site that explains the technicality "IEEE 754 binary floating point representation" quite detailed and understandable. A more easy to understand and theoretical explanation is the video of jan Misali how floating point works.
In short: floating point numbers are stored as a formula that can be used to calculate the exact value. It is not stored as 'the number before and the number after the point'.

Regardless, maybe you can elaborate more on why you need this to receive more helpful answers.

harlekintiger
  • 337
  • 7
  • 22