I have an array of Strings that represent Binary numbers (without leading zeroes) that I want to convert to their corresponding base 10 numbers. Consider:
bi
public Integer binaryToInteger(String binary){
char[] numbers = binary.toCharArray();
Integer result = 0;
int count = 0;
for(int i=numbers.length-1;i>=0;i--){
if(numbers[i]=='1')result+=(int)Math.pow(2, count);
count++;
}
return result;
}
I guess I'm even more bored! Modified Hassan's answer to function correctly.
If you're worried about performance, Integer.parseInt()
and Math.pow()
are too expensive. You can use bit manipulation to do the same thing twice as fast (based on my experience):
final int num = 87;
String biStr = Integer.toBinaryString(num);
System.out.println(" Input Number: " + num + " toBinary "+ biStr);
int dec = binaryStringToDecimal(biStr);
System.out.println("Output Number: " + dec + " toBinary "+Integer.toBinaryString(dec));
Where
int binaryStringToDecimal(String biString){
int n = biString.length();
int decimal = 0;
for (int d = 0; d < n; d++){
// append a bit=0 (i.e. shift left)
decimal = decimal << 1;
// if biStr[d] is 1, flip last added bit=0 to 1
if (biString.charAt(d) == '1'){
decimal = decimal | 1; // e.g. dec = 110 | (00)1 = 111
}
}
return decimal;
}
Output:
Input Number: 87 toBinary 1010111
Output Number: 87 toBinary 1010111
This might work:
public int binaryToInteger(String binary) {
char[] numbers = binary.toCharArray();
int result = 0;
for(int i=numbers.length - 1; i>=0; i--)
if(numbers[i]=='1')
result += Math.pow(2, (numbers.length-i - 1));
return result;
}