Write a program to convert Binary to Decimal number system


The program begins by importing the Scanner class from the java.util package, which allows user input to be read from the console. Then a class named Binary_Decimal is defined, which contains the main method that executes the program.

Inside the main method, the program declares and initializes variables to be used in the conversion process. The bin variable stores the binary number entered by the user, and the dec variable will hold the decimal equivalent. The i variable is an index used to keep track of the current power of 2 being used in the conversion. The rem variable holds the remainder of the binary number divided by 10.

The program then prompts the user to enter a binary number using System.out.print and reads the input value using the Scanner class.

After that, the program enters a while loop that runs as long as the binary number is not equal to 0. Inside the loop, the program calculates the remainder of the division of the binary number by 10 and stores it in the rem variable. The decimal equivalent is then calculated by adding the product of rem and i to the dec variable. The i index is then doubled to move to the next power of 2, and the binary number is divided by 10 to move to the next digit.

After the loop completes, the dec variable contains the decimal equivalent of the binary number. The program then prints the decimal number to the console using System.out.println.

Source Code

import java.util.Scanner;
class Binary_Decimal
{
	public static void main(String[] args) 
	{
		Scanner input = new Scanner(System.in);
		long bin, dec = 0, i = 1, rem;
		System.out.print("Enter The Binary Number: ");
		bin = input.nextLong();		
		System.out.println("Binary Number: " + bin);
		while (bin != 0) 
		{
			rem = bin % 10;
			dec = dec + rem * i;
			i = i * 2;
			bin = bin / 10;
		}
		System.out.println("Decimal Number: " + dec);
	}
}
 

Output

Enter The Binary Number: 100111
Binary Number: 100111
Decimal Number: 39

Example Programs