In this example we will convert binary to decimal using java. We will use this logic
11 ==>> 1*2^1+1*2^0 == > 3
110 ==> 1*2^2+1*2^1+0*2^0 ==> 6
package com.javaproficiency;
public class BinaryToDecimal {
public static void main(String[] args) {
System.out.println(" decimal number ="+ getDecimalFromBinary(11));
}
public static int getDecimalFromBinary(int num ){
int decimal = 0 ;
int p = 0;
while ( num > 0) {
decimal += num %10 * Math.pow(2, p );
num = num /10;
p++;
}
return decimal;
}
}
11 ==>> 1*2^1+1*2^0 == > 3
110 ==> 1*2^2+1*2^1+0*2^0 ==> 6
package com.javaproficiency;
public class BinaryToDecimal {
public static void main(String[] args) {
System.out.println(" decimal number ="+ getDecimalFromBinary(11));
}
public static int getDecimalFromBinary(int num ){
int decimal = 0 ;
int p = 0;
while ( num > 0) {
decimal += num %10 * Math.pow(2, p );
num = num /10;
p++;
}
return decimal;
}
}
Output:
decimal number = 3
No comments:
Post a Comment