When the numbers are represented in base 2, those are called binary numbers. From this article, we are going to convert the integer numbers to the binary format using a recursive function. Let’s take an example and see how this conversion takes place.

Consider an integer number 23 = 16 + 4 + 2 + 1 Binary representation = 10111

This is how it’s done manually;

When the value becomes 1, stop the division and connect all the remainders from the bottom to top including the last value and make it the first digit. This whole process is done using a recursive function in the below example, which calls the same function over and over again until the base condition is met. In this example, base case is to check whether the number is equal to zero or not.

public static String BinaryRecursion(int number){

    	StringBuilder sBuilder = new StringBuilder();  
      if(number > 0){

         //get the remainder of the number when divided with 2
         int remainder = number % 2;

         //get the whole number after the division
         number /=  2;

         sBuilder.append(BinaryRecursion(number))
            		.append("")
            		.append(String.valueOf(remainder));
         return sBuilder.toString();
      }
      else {
        return sBuilder.toString();
      }
}

Now call the function from the main menu

public static void main(String[] args){

      System.out.print("Number to convert into a binary: ");
      Scanner input = new Scanner(System.in);
      int number = input.nextInt();
        
      System.out.println("Binary of "+ number + " is: "
                           + BinaryRecursion(number));
      input.close();
}

Code Explanation

In our example, first, we create a static method which takes one integer argument as the parameter and returns a string. In here, we are going to use the StringBuilder class to append the results to each other and converts the output builder object to a string using toString() method. The basic logic behind the conversion is to divide the particular number by 2 and store the remainder in a variable. Also, we need to store the integer value of the number after dividing by 2. Next, we call the function again and append its result with the remainder we got. After the base condition (number == 0) is met, it returns the StringBuilder object from the method and printed out to the user.

Output

Please enter a number to convert into a binary: 8
Binary of 8 is: 1000

Please enter a number to convert into a binary: 290
Binary of 290 is: 100100010

Recommended Reading

 

Last modified: March 19, 2019