0

How can i convert a decimal into binary? Is there any built in method which i can use to convert decimal into binary?

Roman C
  • 49,761
  • 33
  • 66
  • 176
Tiash
  • 109
  • 3
  • 14

3 Answers3

3

I assume you want the binary representation of an integer number. You could use Integer.toBinaryString(int) -

System.out.println(Integer.toBinaryString(0));
System.out.println(Integer.toBinaryString(255));
System.out.println(Integer.toBinaryString(-1));

Output is (the expected)

0
11111111
11111111111111111111111111111111

If my assumption is incorrect and you want the hex representation you can always use Integer.toHexString(int)

System.out.println(Integer.toHexString(255));

Which will get

ff

Finally, there's Integer.toOctalString(int) if you need that. And, to reverse these operations there is Integer.parseInt(String, int) where the second argument is the radix.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
3

you can use this method Integer.toBinaryString() it's built-in in java

mkazma
  • 572
  • 3
  • 11
  • 29
1

The java.lang package provides the functionality to convert a decimal number into a binary number. The method toBinaryString() comes in handy for such purpose. Bellow is the code:

import java.lang.*;
import java.io.*;
public class DecimalToBinary{
  public static void main(String args[]) throws IOException{
  BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
  System.out.println("Enter the decimal value:");
  String hex = bf.readLine();
  int i = Integer.parseInt(hex);  
  String by = Integer.toBinaryString(i);
  System.out.println("Binary: " + by);
  }
}  
user3250183
  • 506
  • 6
  • 19