In the previous lesson, we covered the conversion of a Decimal to Binary. Here, you will learn how to convert Binary to Decimal in Java. There are a couple of ways:
- Using the parseInt() method
- With custom logic
Convert Binary to Decimal in Java using the parseInt() method
We can use the parseInt(String s, int radix) method of Integer class that parses the String argument as a signed integer in the radix specified by the second argument.
Example
class Test { public static void main(String[] args) { System.out.println(Integer.parseInt("1010", 2)); System.out.println(Integer.parseInt("1001001", 2)); System.out.println(Integer.parseInt("1100010", 2)); } }
Output: 10 73 98
Parse Binary to Decimal with custom logic
We can also write the program without using the pre-defined methods, like in the following example:
public class Test { public static void main(String[] args) { System.out.println(getDecimal(1010)); System.out.println(getDecimal(1001001)); System.out.println(getDecimal(1100010)); } public static int getDecimal(int binary) { int decimal = 0; int n = 0; while (true) { if (binary == 0) { break; } else { int temp = binary % 10; decimal += temp * Math.pow(2, n); binary = binary / 10; n++; } } return decimal; } }
Output: 10 73 98
This code defines a static method getDecimal() that converts a binary number passed as an argument to its decimal representation using a while loop.
That’s it.
Happy coding!