Given a Binary value the task is to convert it into Decimal value.
To convert Binary value to Decimal value we multiple each bit from right to left with 2 raised to the power starting from 0 and increasing towards left and then sum all the values.
Example 1: Consider a Binary value 111001. 1*25+1*24+1*23+0*22+0*21+1*20 = 32+16+8+0+0+1 = 57.
Example 2: Consider a Binary value 101. 1*22+0*21+1*20 = 4+0+1 = 5.
Java
import java.util.*;
public class BinaryDecimal
{
public static void main(String args[])
{
int r=0,bin=0;int dec=0;int pos=0;
Scanner sc=new Scanner(System.in);
System.out.print("Binary Value: ");
bin=sc.nextInt();
while(bin>0)
{
r=bin%10;
dec=dec+(r*(int)Math.pow(2,pos));
pos++;
bin=bin/10;
}
System.out.println("Decimal Value: "+dec);
}
}Java