We can convert from binary to decimal values, however, there are many instances where we want to go the other direction. Having a binary number can assist in computing permutations of a set, as well as many other practical applications. Today, you will write a function that will perform the computation the opposite direction.
Details
Write a function called convert_to_binary(integer)
in a file called base_conversion.py. This function takes
one integer parameter: the decimal number to convert to base-2.
This function should
return a string representation of integer
in the
base-2.
Make sure your program handles all necessary cases gracefully. What additional test cases should you check?
Sample Test Cases
Function Call | Expected Output |
---|---|
convert_to_binary(2) | 10 |
convert_to_binary(3) | 11 |
convert_to_binary(5) | 101 |
Hint
-
You are going to use the accumulator pattern to accumulate a string that represents the input integer converted to the specified base.
-
Inside the loop calculate the quotient and remainder of dividing the input integer by the new base. The remainder is a place value (a single bit) of the converted integer and should be accumulated.
-
The quotient of the previous iteration is the input integer of the next iteration. At the bottom of the loop, update the input integer to be the quotient.
Challenge
Another very popular numeric system is known as hexadecimal. hexadecimal is simply a base 16 number system. However, we only have 10 "numeric" digits to work with in our number system. We typically get around this by using letters for the rest of the numbers. So, 'A' is used to represent the digit 10, 'B' for the digit 11, and up to 'F' representing the digit 15.
Add a function called convert_to_hexadecimal(integer)
function that converts the parameter to base 16. Remember that
since the ASCII values of the upper case characters are
sequential, you don't need 6 conditionals to handle the
characters in a hexadecimal number.
Submission
Please show your source code and run your programs for the instructor or lab assistant. Only a programs that have perfect style and flawless functionality will be accepted as complete.