Base conversion is no longer tested on the AP CS A Exam. This exercise remains available as practice with recursion.
This practice problem includes algorithms to convert between base 10 and another base. Base 2 is used as the other base; however, the algorithms work for conversion between base 10 and any other base.
Part (a): Base 10 to base 2
To convert a number from decimal (base 10) into another base: Divide the number to be converted by the desired base. Keep both the quotient and the remainider. Continue dividing until the quotient is 0. Read the remainders from bottom to top.
Example 1 from base 10
12
in base 10 is __ in base 2.
12 / 2 = 6 R0
6 / 2 = 3 R0
3 / 2 = 1 R1
1 / 2 = 0 R1
12
in base 10 is 1100
in base 2
Example 2 from base 10
34
in base 10 is __ in base 2.
34 / 2 = 17 R0
17 / 2 = 8 R1
8 / 2 = 4 R0
4 / 2 = 2 R0
2 / 2 = 1 R0
1 / 2 = 0 R1
34
in base 10 is 100010
in base 2.
toBinary
method
Method toBinary
recursively prints the binary (base 2) representation of inBase10
. For example, toBinary(12)
prints 1100
. toBinary(34)
prints 100010
.
// Precondition: inBase10 >= 0
public static void toBinary(int inBase10)
{
if(inBase10 <= 1)
{
System.out.print(inBase10);
return;
}
/* to be completed in part (a) */
}
Give code to replace /* to be completed in part (a) */
.
Part (b): Base 2 to base 10
Write the place value of each digit under each digit. The place value of the rightmost digit is the base to the 0 power. The place value of the digit 2nd from the right is the base to the power of 1. The pattern continues.
Multiply each digit by its place value. Add the results. The sum is the number in base 10.
Example 1 to base 10
11010
in base 2 is __ in base 10.
1 1 0 1 0
2^4 2^3 2^2 2^1 2^0
16 + 8 + 0 + 2 + 0 = 26
11010
in base 2 is 26
in base 10
Example 2 to base 10
100010
in base 2 is __ in base 10.
1 0 0 0 1 0
2^5 2^4 2^3 2^2 2^1 2^0
32 + 0 + 0 + 0 + 2 + 0 = 34
100010
in base 2 is 34
in base 10.
toDecimal
method
Method toDecimal
recursively converts inBase2
to an decimal (base 10) number and returns the decimal representation. For example, toDecimal("11010")
returns 26
. toDecimal("100010")
returns 34
.
// Precondition: inBase2.length() > 0
public static int toDecimal(String inBase2)
{
if(inBase2.length() == 0)
return 0;
/* to be completed in part (b) */
}
Give code to replace /* to be completed in part (b) */
.
Solution & comments
See the Recursive base conversion practice problem solution or review it with AP CS Tutor Brandon Horn.