Java program to convert a binary number to Decimal [Shortcut Method]
Java program to convert a binary number to Decimal [Shortcut Method]
I have used basic String functions and explicit type casting to achieve the goal.. Please find the code below:-
import java.util.*;
public class binarytodecimal
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the binary number");
int bin=sc.nextInt();
int sum=0,i,j;
String bina = Integer.toString(bin);
int len=bina.length()-1;
for(i=len,j=0;i>=0&&j<=len;i--,j++)
{
sum+=(Character.getNumericValue(bina.charAt(i)))*Math.pow(2,j);
}
System.out.println("The decimal number is:"+sum);
}
}
No comments: