Senin, 21 Maret 2016

Java Example Program to convert binary to decimal


  • Famous interview java question on conversions . 
  • We can convert binary to decimal in two ways
    1.Using Integer.parseInt() method
    2.Using custom logic



1.Write a Java Program to convert binary to decimal number in java without using Integer.parseInt() method.

  1. import java.util.Scanner;
  2. public class DecimalFromBinary {
  3.  
  4.     /**
  5.      *www.instanceofjava.com
  6.      */
  7.  
  8.  public static void main(String[] args) {
  9.         
  10.  Scanner in = new Scanner( System.in );
  11.  System.out.println("Enter a binary number: ");
  12.  
  13.   int  binarynum =in.nextInt();
  14.   int binary=binarynum;
  15.         
  16. int decimal = 0;
  17. int power = 0;
  18.  
  19. while(true){
  20.  
  21.  if(binary == 0){
  22.  
  23.         break;
  24.  
  25.  } else {
  26.  
  27.    int tmp = binary%10;
  28.    decimal += tmp*Math.pow(2, power);
  29.    binary = binary/10;
  30.    power++;
  31.  
  32.  }
  33. }
  34.         System.out.println("Binary="+binary+" Decimal="+decimal); ;
  35. }
  36.  
  37. }

Output:


  1. Enter a binary number: 
  2. 101
  3. Binary=101 Decimal=5




2.Write a Java Program to convert binary to decimal number in java using Integer.parseInt() method.



  1. import java.util.Scanner;
  2. public class ConvertBinaryToDecimal{
  3.  
  4.     /**
  5.      *www.instanceofjava.com
  6.      */
  7.  
  8.  public static void main(String[] args) {
  9.         
  10.  Scanner in = new Scanner( System.in );
  11.  
  12.  System.out.println("Enter a binary number: ");
  13.  String binaryString =input.nextLine();
  14.  
  15.  System.out.println("Result: "+Integer.parseInt(binaryString,2));

  16.  
  17. }
  18.  
  19. }


Output:


  1. Enter a binary number:
  2. 001
  3. Result: 1

java program to convert binary to decimal


You Might like:

Bagikan

Jangan lewatkan

Java Example Program to convert binary to decimal
4/ 5
Oleh

Subscribe via email

Suka dengan artikel di atas? Tambahkan email Anda untuk berlangganan.