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?
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.
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.
Integer.toBinaryString()
is an in-built method and will do quite well.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With