Sunday 25 June 2017

Write a program to convert binary to decimal number


Description:
Write a program to convert binary format to decimal number using numeric operations. Below example shows how to convert binary to decimal format using numeric operations.

Code:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package com.govindsblog.algos;
 
public class BinaryToDecimal {
 
    public int getDecimalFromBinary(int binary){
         
        int decimal = 0;
        int power = 0;
        while(true){
            if(binary == 0){
                break;
            } else {
                int tmp = binary%10;
                decimal += tmp*Math.pow(2, power);
                binary = binary/10;
                power++;
            }
        }
        return decimal;
    }
     
    public static void main(String a[]){
        BinaryToDecimal bd = new BinaryToDecimal();
        System.out.println("11 ===> "+bd.getDecimalFromBinary(11));
        System.out.println("110 ===> "+bd.getDecimalFromBinary(110));
        System.out.println("100110 ===> "+bd.getDecimalFromBinary(100110));
    }
}

Output:
11 ===> 3
110 ===> 6
100110 ===> 38

No comments:

Post a Comment