Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Decimal to Binary Java

I am trying to convert decimal to binary numbers from the user's input using Java.

I'm getting errors.

package reversedBinary; import java.util.Scanner;  public class ReversedBinary {   public static void main(String[] args) {     int number;       Scanner in = new Scanner(System.in);      System.out.println("Enter a positive integer");     number=in.nextInt();      if (number <0)         System.out.println("Error: Not a positive integer");     else {           System.out.print("Convert to binary is:");         System.out.print(binaryform(number)); }  }  private static Object binaryform(int number) {     int remainder;      if (number <=1) {         System.out.print(number);      }      remainder= number %2;      binaryform(number >>1);     System.out.print(remainder);      {      return null; } } } 

How do I convert Decimal to Binary in Java?

like image 236
Euridice01 Avatar asked Feb 09 '13 03:02

Euridice01


People also ask

How do I convert decimal to binary?

An easy method of converting decimal to binary number equivalents is to write down the decimal number and to continually divide-by-2 (two) to give a result and a remainder of either a “1” or a “0” until the final result equals zero. So for example. Convert the decimal number 29410 into its binary number equivalent.

How do you code binary in Java?

To convert decimal to binary, Java has a method “Integer. toBinaryString()”. The method returns a string representation of the integer argument as an unsigned integer in base 2. Let us first declare and initialize an integer variable.


2 Answers

Integer.toBinaryString() is an in-built method and will do quite well.

like image 99
Vaibhav Avatar answered Oct 03 '22 18:10

Vaibhav


Integer.toString(n,8) // decimal to octal  Integer.toString(n,2) // decimal to binary  Integer.toString(n,16) //decimal to Hex 

where n = decimal number.

like image 34
Jesse Pinkman Avatar answered Oct 03 '22 18:10

Jesse Pinkman