Overview
A binary number is a number which is composed of digits 1 and 0 such as 110011. A decimal number is a number which is composed of digits 0 to 9 such as 130672.
It is a common requirement in computer programming to convert a decimal number to binary format and vice-versa.
In this post, we will focus on different ways a decimal number can be converted to its equivalent binary number in java.
Logic
To convert a decimal number into binary, a series of steps are performed. In every step, the number is divided by 2 (since the base of binary number is 2) and the remainder is stored.
Also, in each step the number is replaced by the quotient of previous step. These steps are performed till the quotient(or the number to be divided in next step) becomes 0.
The number formed by merging all the remainders is the resultant Binary Number.

For Example, suppose the number to be converted to binary is 24. It is divided by 2 in a sequence of steps as :

DivisionQuotientRemainder
25 / 2121
12 / 260
6 / 230
3 / 211
1 / 201

Now, merging the remainders of all steps starting from last step to step 1(or in reverse order of division), the binary number is 11001.

This post will focus on elaborating different methods of converting a decimal number to binary using java.

Method 1 : Using Array
Code to convert a decimal number to binary is given below. This code loops over the number till it remains greater than zero.
In every iteration, the number is divided by 2 and its remainder is held in an integer array.
After the loop completes, this array is iterated to print the digits.

static void usingArray() {
   //initialize array
   int binary[] = new int[20];
   // declare the decimal number to be converted to binary
   int decimalNumber = 25;
   int index = 0;
   // loop till the number is greater than 0
   while (decimalNumber > 0) {
      // divide the number by 2 using modulus operator so that we get the remainder
      int remainder = decimalNumber % 2;
      // store the remainder in array
      binary[index++] = remainder;
      // divide the number to get the quotient and assign it back to the number
      decimalNumber = decimalNumber / 2;
   }
   // loop over the array backwards and print the binary number
   for (int i = index - 1; i >= 0; i--) {
      System.out.print(binary[i]);
   }
}

Method 2 : Using StringBuffer
This method is similar to the above method but instead of using an array to hold the remainder values, we use a java.lang.StringBuffer.
After the loop, the StringBuffer is reversed since the remainder digits have been added from the start and binary number is counted from the end.
The reversed StringBuffer is then converted to a String.

static void usingStringBuffer() {
   // declare the decimal number to be converted to binary
   int decimalNumber = 25;
   // initialize stringbuffer which will hold the binary number
   StringBuffer binaryBuffer = new StringBuffer();
   // loop till the number is greater than 0
   while (decimalNumber > 0) {
      // divide the number by 2 using modulus operator so that we get the remainder
      int remainder = decimalNumber % 2;
      // add the remainder to string buffer
      binaryBuffer.append(remainder);
      // divide the number to get the quotient and assign it back to the number
      decimalNumber = decimalNumber / 2;
   }
   //reverse the buffer and convert it to string
   String binaryNumber = binaryBuffer.reverse().toString();
   System.out.println(binaryNumber);
}

Method 3 : Using Integer wrapper class method
java.lang.Integer class has a method toBinaryString() which takes an integer and converts it to its binary equivalent in String format.

static void usingWrapperClass() {
   // declare the decimal number to be converted to binary
   int decimalNumber = 25;
   //convert the decimal number to binary using Integer class method
   String binaryNumber = Integer.toBinaryString(decimalNumber);
   System.out.println(binaryNumber);
}

Method 4 : Using toString() method of Integer wrapper class
java.lang.Integer class has a toBinaryString() method which takes an integer and the base (or radix) of the number system in which the integer needs to be converted.
Since the base of binary number system is 2, we pass it to the toString() method and get the binary representation of the supplied decimal number.

static void usingToStringMethod() {
   // declare the decimal number to be converted to binary
   int decimalNumber = 25;
   //convert the number to string using desired base
   String binaryNumber = Integer.toString(decimalNumber, 2);
   System.out.println(binaryNumber);
}

Method 5 : Using Recursion
This method is similar to Method 1 except that instead of looping over the number, we call the method recursively passing the number divided by 2 as argument.
The method is called till the number reduces to either 0 or 1. At this point, the number has been converted to its binary equivalent and hence the recursion ends.

static void usingRecursion() {
   // declare the decimal number to be converted to binary
   int decimalNumber = 25;
   // call the method which converts the number to binary
   printBinaryform(decimalNumber);
}
 
static void printBinaryform(int number) {
   int remainder;
   // check if the number is 0 or 1, then it has been converted to binary
   if (number <= 1) {
      System.out.print(number);
      return;
   }
   // divide the number by 2 using modulus operator so that we get the remainder
   remainder = number % 2;
   //call method again with the quotient as the number
   printBinaryform(number / 2);
   System.out.print(remainder);
}

Method 6 : Using Stack
This method is also similar to Method 1. It uses a java.util.Stack to hold the remainders of division. A Stack is a LIFO data structure.
Elements added first are retrieved last from it. Hence the remainders added to it are retrieved in reverse order.
For retrieving elements from the stack, we iterate over it till it becomes empty.
Elements are added to a Stack using push() method and retrieved using pop() method.

static void usingStack() {
   // initialize stack
   Stack stack = new Stack();
   // declare the decimal number to be converted to binary
   int decimalNumber = 25;
   // loop till the number is greater than 0
   while (decimalNumber > 0) {
      // divide the number by 2 using modulus operator so that we get the
      // remainder
      int remainder = decimalNumber % 2;
      // push the remainder at the top of stack
      stack.push(remainder);
      // divide the number to get the quotient and assign it back to the number
      decimalNumber = decimalNumber / 2;
   }
   // loop over stack till it becomes empty
   while (!stack.isEmpty()) {
      // remove topmost elements from the stack
      System.out.print(stack.pop());
   }
}

Let’s tweak in :

  1. Every number belongs to a number system. Each number system has its own base or radix.
    Thus every number has a base which tells us about the number system of this number.
    Following are the common number systems and their base (or radix) :

    Binary Number System2
    Octal Number System8
    Decimal Number System10
    Hexadecimal Number System16
  2. The result of toBinaryString() method of java.lang.Integer class will be different for positive and negative numbers.
    That is, toBinaryString(25) and toBinaryString(-25) will give different values.
  3. Use java.lang.StringBuffer in place of java.lang.String when there are multiple String manipulations involved.
    This is because each String manipulation creates a new object while in case of StringBuffer, same object is manipulated.
  4. java.lang.Integer class has toOctalString() and toHexString() methods to convert a decimal to Octal and Hexadecimal equivalents respectively.

There can be many other approaches to convert a decimal to binary. If you can think of, let’s add it to the list.

0

Share your thoughts !!

Close Menu

Never Miss an article !

Get the new post delivered straight into your inbox, enter your email and hit the button

You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

codippa will use the information you provide on this form to be in touch with you and to provide updates and marketing.