Here you will get the program to change over binary to decimal in Java.
There are mainly two different ways to change over a binary number to decimal number in Java.
- By using parseInt() technique for Integer class.
- By using a client-defined rationale.
Program to Convert Binary to Decimal in Java
By using Integer.parseInt()
Integer.parseInt() technique takes two contentions. The first contention is a string and the second contention is the base or radix wherein we need to change over the number.
import java.util.Scanner;
class BinaryToDecimal
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
System.out.println("Enter a binary number:");
String n=s.nextLine();
System.out.println(Integer.parseInt(n,2));
}
}
The yield is the integer spoken to by the string contention in the predefined radix. The following is the program for it.
Without using Integer.parseInt()
In this strategy, we need to define our very own rationale for converting binary number to decimal. The methodology that we will use here is referenced in underneath model.
The program that actualizes the above approach is referenced underneath.
import java.util.Scanner;
class BinaryToDecimal
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
System.out.println("Enter a binary number:");
int n=s.nextInt();
int decimal=0,p=0;
while(n!=0)
{
decimal+=((n%10)*Math.pow(2,p));
n=n/10;
p++;
}
System.out.println(decimal);
}
}
Output