How to Convert Binary to Decimal in Java

There are two methods to convert binary to decimal.

  • Using Integer.parseInt() method
  • Using user-defined logic

Using Integer.parseInt() method

The parseInt() is a static method of Integer wrapper class. It converts string to integer with specified radix or base. It takes two arguments. First for binary string, and second for radix (in which we have to convert the number). It returns the integer represented by the string argument in the specified radix. The signature of the method is given below:

public static int parseInt(String str,int radix)

Example

In the following example, we have taken two variable d1 and d2 of type int, which stores the converted decimal value of the corresponding binary number. The Integer is a wrapper class. It invokes the parseInt(string binary_number,int radix) method of Integer class. It parses two arguments first one is the string of boolean number and the second one is the radix. It returns the corresponding decimal number. The first println statement prints the decimal value of 101101 and the second println statement prints the decimal value of 1001001.

Output

Using user-defined logic

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

Example

In the following example, we have taken a variable bnum (represent binary number) of type integer and initialize 1001 to it. We have defined two more int variables dnum (represent decimal number) and pwr (represent power) and initialize 0 to both.

Let’s see how the body of the loop will execute?

The body of the while loop has three statements.

The first statement calculates the required decimal number. bnum%10 calculates the remainder. Math.pow(2,pwr) is the method of java.lang.Math class, which returns the value of the first argument raised to the power of the second argument. After getting both results, we have multiplied both values, and add and store the resultant to the dnum variable.

The second statement updates the value of bnum, i.e., it divides the bnum by 10 and takes the quotient. The while loop will execute until the specified condition becomes false. The third statement increments by 1 in the pwr (power) variable. When the specified condition gives false, then the loop will terminate the execution. The println statement prints the equivalent decimal number, which is stored in dnum variable.

Output

Pin It on Pinterest

Share This