Convert Binary Number To Decimal Number in Java

Today you are here to learn and to convert binary number to decimal number in java.

This is my experience in interview (Java Interview). Firstly the interview was good and i got placed in one of the top MNC.

The interview was purely based on JAVA.

After initial rounds including technical interview there was a system test in which i got a program to convert binary number to decimal number without using Integer.parseInt() method (Update: Scroll down to learn java program to convert binary number to decimal number using Integer.parseInt() method) and to find the area of circle.

Though the latter was easy to write as well as to execute. You can find the area of circle program here.

Convert Binary Number To Decimal Number in Java

Lets dig into former program that is, to convert binary number to decimal number,

Example: Convert Binary Number To Decimal Number in Java

Also Read – Bubble Sort Java Program

import java.util.Scanner;

public class Binary_to_Decimal{

public static void main(String[] args){

Scanner sc = new Scanner(System.in);
System.out.println("Please enter a Binary Number: ");

int binary_Number = sc.nextInt();
int binary = binary_Number;

int decimal = 0;
int to_Power = 0;

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

System.out.println("Binary Number = " + binary + ", Decimal Number = " + decimal);
}
}

Output:

Please enter a Binary Number: 1000

Binary Number = 0, Decimal Number = 8


Example: Convert Binary Number To Decimal Number in Java using Integer.parseInt() method

Also Read – Area of Rectangle Program in Java

import java.util.Scanner;

public class Binary_to_Decimal{

public static void main(String[] args) {

Scanner sc = new Scanner( System.in);

System.out.println("Please enter a Binary Number: ");
String binary_Number = sc.nextLine();

System.out.println("Result: " + Integer.parseInt(binary_Number,2));
}

}

Output:

Please enter a Binary Number: 1000

Result: 8

About the author

admin

View all posts

Leave a Reply

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