How to Convert Decimal to Binary in Java

There are two methods to convert Decimal to Binary.

  • Using toBinaryString() method
  • Using user-defined logic

Using Integer.toBinaryString()

The toBinaryString() is a static method of Integer wrapper class. It returns the string representation of unsigned integer represented by the argument in binary. The signature of the toBinaryString() method is given below:

public static String toBinaryString(int i)

Where i is an integer to be converted to String.

Example

In the following example, we have passed two integers 25 and 45 as arguments of toBinaryString() method and store the converted value in the String variable str and str1 respectively. The println statements print the corresponding binary value of 25 and 45 respectively.

Output

Using user defined logic

In this method, we have to define our own logic for converting decimal to binary.

Example

In the following example, we have defined a class DecimaltoBinary. Inside the class, we have defined toString() method which accepts an integer n and returns the corresponding binary string. The number n will be repeatedly divided by 2 until we obtain 0 and the remainder will concatenate. The string variable ‘binary’ holds the result.

The while loop has the condition n>0 which will repeatedly perform the operations in the while block until n does not become 0. The body of the while loop contains three statements.

The first statement finds the remainder on dividing n by 2, which is obtained by using a modulo operator.

The second statement concatenates the remainder (rem) to the binary representation we have obtained so far. Note that we have written ‘rem+binary’ not ‘binary+rem.’ That’s why the last remainder will be the first bit in the binary representation.

The third statement updates the value of n, i.e., it divides the value by 2 and takes the quotient.

When we invoke the method toBinary() with decimal=0 (which is the special check for n==0 is not present). The variable binary will be initialized to “”. The condition n!=0 is false, so the loop will not be execute even once and the result returned would be “”, which is not the correct answer, the correct answer is “0“. Because of this we add a special check for decimal=0.

Output

Pin It on Pinterest

Share This