Write a Java Program to convert a binary number to its corresponding decimal representation.

Example:

The standard way of converting any binary number to its decimal representation is to multiply each of the binary digits with the value of 2 raised to the power to its index (the position from right – 1 ) and sum them up.

Refer to the picture given below for clear understanding.

Binary to Decimal

Let’s implement the same in Java.

Convert Binary to Decimal in Java using While Loop

Output

Enter a Binary
101
Decimal: 5

Convert Binary to Decimal in Java using Recursion

The approach is the same as the above method but in a recursive way. We need to extract the last digit from the received binary number ( only when it is not a single-digit) on each recursive call.

Then we need to multiply it with its corresponding value of 2 raised to the power its position in the original binary number from the right and sum it up with the next recursive call result.

we need to eliminate the last digit from the binary number on the next recursive call.

Output

Enter a Binary
1111
Decimal: 15

If you have any doubts or suggestions then below.

Leave a Reply

Close Menu