Tuesday, 13 September 2016

Java program to Convert Binary To Decimal?

The decimal number is equal to the sum of powers of 2 of the binary number's '1' digits place . Here we add only those powers whose binary is one. For Example :-
Binary Number
1
1
1
0
0
0
0
Power of 2
26
25
24
23
22
21
20
Value
64
32
16
8
4
2
 1

                       64  +   32   +   16   +    0   +   0   +   0   +   0   = 112


public class BinaryToDecimal {

public static void getDecimal(int num){
int binary = num;
int i = 0;
int decimal = 0;
while(num > 0){
int temp = num % 10;
decimal+=Math.pow(2, i++)*temp; 
num = num / 10;
}
System.out.println("DECIMAL OF "+binary+" : "+decimal);
}
public static void main(String[] args) {
BinaryToDecimal.getDecimal(11);
BinaryToDecimal.getDecimal(1110000);
}

}

Program Output :-

DECIMAL OF 11 : 3
DECIMAL OF 1110000 : 112


No comments:

Post a Comment