Showing posts with label binary to decimal conversion. Show all posts
Showing posts with label binary to decimal conversion. Show all posts

How to Convert a Binary Number to Decimal Equivalent in Java?

Write a Java program to convert the binary number into the decimal number.


Java program to convert the binary number into the decimal number


Decimal Number System - 

The decimal number system consists of digits from 0 to 9.


Binary Number System - 

The binary number system consists of only two digits which are 0 and 1. 


PROGRAM :


import java.util.Scanner;

class bintodec

{

 public static void main(String args[])

 { 

  int p=0,d=0,t=0,tmp=0;


  Scanner sc=new Scanner(System.in);

  System.out.print("\nEnter the binary no.: ");

  int b=sc.nextInt();  


  System.out.print("\nThe decimal equivalent        

                     of "+b+" is : ");  


  while(true)

  {

   if(b==0)

   {

    break;

   }

   else

   {

    tmp=b%10;

    t=tmp*(int)Math.pow(2,p);

    d=d+t;

    b=b/10;

    p++;

   }

  }

  System.out.print(d);

 }

}


Output :

Enter the binary no.: 10101

The decimal equivalent of 10101 is : 20

 

Read also :

How to convert decimal to binary program in Java?