Tuesday, February 24, 2015

Converting binary to decimal


Algorithm works by getting last digit in each iteration and then multiply it by 2^position, where position starts from zero.




Do the modulus to get the last number, each time increase the power by 1.

public int binary(int binary)
{
int power = 0;
int digit = 0;
while(binary!=0){
int last= binary%10;
digit += last*Math.pow(2,power); //Math.pow(2, power) should be replaced by (1 << power):
power++;
binary = binary/10;
}
}

No comments:

Post a Comment

java-8-streams-map-examples

package com.mkyong.java8; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; import java.util.List; im...