Convert Decimal to Binary Number in Java

Exercise:

Write a Java Program to convert decimal to binary in java.

Click Here to View the Solution!
 public class DecimalToBinary {
  
     public static void main(String[] args) {
         int number = 29;
         long binary = convertDecimalToBinary(number);
         System.out.printf("%d in decimal = %d in binary", number, binary);
     }
  
     public static long convertDecimalToBinary(int n)
     {
         long binaryNumber = 0;
         int remainder, i = 1, step = 1;
  
         while (n!=0)
         {
             remainder = n % 2;
             System.out.printf("Step %d: %d/2, Remainder = %d, Quotient = %d\n", step++, n, remainder, n/2);
             n /= 2;
             binaryNumber += remainder * i;
             i *= 10;
         }
         return binaryNumber;
     }
 } 
Click Here to View the Output!
 Step 1: 29/2, Remainder = 1, Quotient = 14
 Step 2: 14/2, Remainder = 0, Quotient = 7
 Step 3: 7/2, Remainder = 1, Quotient = 3
 Step 4: 3/2, Remainder = 1, Quotient = 1
 Step 5: 1/2, Remainder = 1, Quotient = 0
 29 in decimal = 11101 in binary
Click Here to View the Explanation!
  • This program deals with transforming a decimal number into a binary number with the help of convertDecimalToBinary() function.
  • In this example the data type for input number (29) is ‘int’.
  • This time remainder of the input number will be taken by dividing it to the number ‘2’.
  • The variables declared in the convertDecimalToBinary() function, keep track of ‘steps’, remainder, and binary value.
  • During the first step of execution, remainder is calibrated and then displayed along with the quotient value in the second statement. (Remainder = 1, Quotient = 14)
  • This process continues as long as the value of ‘number’ does not tend to be ‘0’. Once the value of ‘number’ becomes equal to ‘0’, the program terminates and returns ‘11101’, which is the binary value for number ‘29’.

%d bloggers like this: