Convert binary to decimal example in Java

convert binary to decimal

convert binary to decimal

We will convert binary number to decimal using following two methods:

  1. Without using Integer.parseInt()
  2. Using Integer.parseInt()

Write a program to convert binary to decimal without using Integer.parseInt()

/**
 * 
 * @author programtalk.com
 *
 */
public class BinaryToDecimal {

	public int convert(int binaryNo) {

		int decimal = 0;
		int power = 0;
		while (true) {
			if (binaryNo == 0) {
				break;
			} else {
				int temp = binaryNo % 10;
				decimal += temp * Math.pow(2, power);
				binaryNo = binaryNo / 10;
				power++;
			}
		}
		return decimal;
	}

	public static void main(String args[]) {
		BinaryToDecimal obj = new BinaryToDecimal();
		System.out.println("Binary : 100  --> Decimal  : " + obj.convert(100));
		System.out.println("Binary : 1101  --> Decimal  : " + obj.convert(1101));
		System.out.println("Binary : 100011  --> Decimal  : " + obj.convert(100011));
	}
}

Output


Binary : 100 --> Decimal : 4
Binary : 1101 --> Decimal : 13
Binary : 100011 --> Decimal : 35

Write a program to convert binary to decimal using Integer.parseInt()

/**
 * 
 * @author programtalk.com
 *
 */
public class BinaryToDecimal {

	public int binaryToDecimal(String binaryStr) {
		// Parses the string argument as a signed integer in the radix
		// specified by the second argument
		return Integer.parseInt(binaryStr, 2);
	}

	public static void main(String args[]) {
		BinaryToDecimal obj = new BinaryToDecimal();
		System.out.println("Binary : 100  --> Decimal  : " + obj.binaryToDecimal("100"));
		System.out.println("Binary : 1101  --> Decimal  : " + obj.binaryToDecimal("1101"));
		System.out.println("Binary : 100011  --> Decimal  : " + obj.binaryToDecimal("100011"));
	}
}

Output


Binary : 100 --> Decimal : 4
Binary : 1101 --> Decimal : 13
Binary : 100011 --> Decimal : 35

Integer.parseInt()

We used Integer.parseInt() in the second example.  The Javadocs about this method

Parses the string argument as a signed integer in the radix specified by the second argument. The characters in the string must all be digits of the specified radix (as determined by whether Character.digit(char, int) returns a nonnegative value), except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a negative value or an ASCII plus sign '+' ('\u002B') to indicate a positive value. The resulting integer value is returned.

In our example we passed the binary String and the radix as 2 which means a binary value. So the parsseInt parses this string we passed as binary and returns the integer value of the binary String.

 

Like this post? Don’t forget to share it!

Leave a Reply

Your email address will not be published. Required fields are marked *