Binary to decimal

Write a program to convert a binary number to decimal number

import java.util.Scanner;
class Binary2Decimal
{
    public static void main()
    {
        long last;
        long decimal=0;
        System.out.println("Enter a number only in base 2");
        Scanner in = new Scanner(System.in);
        long a = in.nextLong();
        long b=a;
        for(int i=0;a>0;i++)
        {
            last= a%10; a=a/10;
            if(last!=0 && last!=1)
            {
                System.out.println("Enter a number only in base 2");
                a = in.nextLong();
                b=a;
            }
        }
        for(int i=0;b>0;i++)
        {
            last= b%10; b=b/10;
            decimal=(int)Math.pow(2,i)*last + decimal;
        }
        System.out.println("Given number in base 2   "+decimal);
    }
}

For any desired program, please comment below. We will try our best to make that program available.

Comments

Popular Posts