How To Convert A Binary Number To Decimal In Java

Sharing is healthy !!

Today you are here to learn how to convert a binary number to decimal 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 and to find the area of circle.

(Update: Scroll down to learn java program to convert binary number to decimal number using Integer.parseInt() method)

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

how to convert a binary number to decimal in java

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

Example: how to convert a binary number to decimal in java

Also Read – Bubble Sort Java Program

import java.util.Scanner;

public class BinaryToDecimal
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a Binary Number: ");

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

int decimal = 0;
int toPower = 0;

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

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

Output:

Please enter a Binary Number: 1000

Binary Number = 0, Decimal Number = 8


Example: how to convert a binary number to decimal in java using Integer.parseInt() method

Also Read – Area of Rectangle Program in Java

import java.util.Scanner;

public class BinaryToDecimalDemo
{
public static void main(String[] args)
{
Scanner sc = new Scanner( System.in);

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

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

}

Output:

Please enter a Binary Number: 1000

Result: 8


conclusion

That’s it guys. This is all about how to convert a binary number to decimal in java.

I hope you have understood the program. You can subscribe to my blog flower brackets if you haven’t already.

Do share this post if you like.

Sharing is healthy !!

Leave a Reply

Your email address will not be published.