Write a Java Program to convert Binary to Integer

The following code illustrates how to convert an Binary to Decimal.The code accepts binary as a string then converts binary to integer in two ways. One way is to use the Integer.valueOf (binary ,2). Another way is writing our own code which are explained in the following example. This program may be asked in core java written exam.

Each digit in a binary has a position

7654 3210 <— position
1001 0101

For converting binary to decimal -> 1* 2^7 + 0 *2^6 + 0*2^5 + 1*2^4 + 0*2^3 + 1*2^2 + 0*2^1 + 1*2^0 where 7,6,5,4,3,2,1,0 are positions */

package net.javaonline;

import java.util.Scanner;

public class JavaBinaryToDecimal {

	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);

		System.out.println("Please enter any Binary Value");

		String binary = sc.next();

		System.out.println("Using Integer.valueOf(binary,2)  Decimal of  "
				+ binary + " is " + Integer.valueOf(binary, 2)); // Converts
																	// Decimal
																	// to Binary
																	// using
																	// toBinaryString(number)
																	// method...

		long decimal = BtoD(binary);

		System.out.println("Using  Own method  BtoD " + binary + " is "
				+ decimal);

	}

	// The BtoD fnction which converts binary to decimal

	public static long BtoD(String binary)

	{

		int i = 0;

		long decimal = 0;

		for (int pos = binary.length() - 1; pos >= 0; pos--) {

			int digit = Character.getNumericValue(binary.charAt(i));

			decimal += digit * Math.pow(2, pos);

			i++;

		}

		return decimal;

	}

}

Running the above program will give the following output

java binary to decimal java binary to decimal1

 

Leave a Reply