Binary to decimal conversion program in java


In this core java programming tutorial we will write a program to perform Binary to decimal conversion in java.



Binary to decimal conversion program in java.


1110 = 1·23  +  1·22  +  1·21  +  0·20 = 14
binary number:
1
1
1
0
power of 2:
23
22
21
20


1111 = 1·23  +  1·22  +  1·21  +  1·20 = 15
binary number:
1
1
1
1
power of 2:
23
22
21
20




Full Program/SourceCode/ example to do Binary to decimal conversion in java >
/** Copyright (c), AnkitMittal www.JavaMadeSoEasy.com */
public class BinaryToDecimalConversionExample {
  
   public static void main(String...args){     
            int decimal=1110;
      System.out.println("binary "+decimal+" = decimal " + binaryToDecimalConverter(decimal));
            decimal=1111;
            System.out.println("binary "+decimal+" = decimal " + binaryToDecimalConverter(decimal));
  }
  
   /*
   * method converts binary number to decimal.
   */
   public static int binaryToDecimalConverter(int binary){     
       int decimal = 0;
       int power = 0;
       while(binary>0){
        decimal += (binary%10) * Math.pow(2, power++);
        binary = binary/10;
       }
       return decimal;
   }
   
}
/*OUTPUT
binary 1110 = decimal 14
binary 1111 = decimal 15
*/

So in this core java programming tutorial we wrote a program on how to to perform Binary to decimal conversion in java.


Previous program                                                                  Next program


Having any doubt? or you you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com (JMSE) on facebook, following on google+ or Twitter.



RELATED LINKS>

>Pattern/Pyramid generating programs








eEdit
Must read for you :