In: Computer Science
Question 3 - Write a java program named BinaryConversion that will convert base 2 numbers to base 10 numbers.
This complete question is already in chegg study! I want to know the answer for that question?
Algorithm: To convert a base2 number to base10 we need to start from the left of the binary number with indexing zero and calculate the cumulative sum of power(2,index)*valueAtIndex .
Lets see an example...
binaryNumber = 10101010
To convert it into decimal we will follow the above algorithm. In the left most side power(2,index) will be power(2,0) which will be 1 and then it will get multiplied by 0 which is value at that index. Have a look at the at the below expantion.
(10101010)₂ = (1 × 2⁷) + (0 × 2⁶) + (1 × 2⁵) + (0 × 2⁴) + (1 × 2³) + (0 × 2²) + (1 × 2¹) + (0 × 2⁰) = (170)₁₀
Have a look at the below code. I have put comments wherever required for better understanding.
import java.lang.Math;
class Main {
// create the function
public static int base10(int binary){
// variable to store the result
int result = 0;
// variable to store power
int power = 0;
while (binary>0){
// find the left most element
int remainder = binary%10;
binary /= 10;
// calculate sum
result+=(Math.pow(2,power)*remainder);
// increment the power
power+=1;
}
// return the result
return result;
}
public static void main(String[] args) {
System.out.println(base10(10101010));
}
}
Happy Learning!