Decimal to Binary
Intermediate · Write the code · from Binary Numbers and Bits: How Computers Represent Data
From the lesson: How do you convert decimal to binary?
There are two common methods, and they always agree. Method 1: subtract place values. List the place values up to the number (32, 16, 8, 4, 2, 1 for anything under 64). Starting from the largest, write 1 if that place value fits into what is left and subtract it, otherwise write 0.
Read this part of the lessonWrite to_binary(n). It takes a whole number n (0 or more) and returns its binary form as a string with no leading zeros. Use repeated division by 2 instead of bin().
to_binary(13) -> '1101'
to_binary(0) -> '0'def to_binary(n):
# Divide by 2 again and again; each remainder is a bit
pass
What Check runs
Your code runs first, then each of these lines, and 2 more that stay hidden. The output must match exactly.
| Runs | Expected output |
|---|---|
| print(to_binary(13)) | 1101 |
| print(to_binary(1)) | 1 |
| print(to_binary(255)) | 11111111 |
More Binary Numbers exercises
- Binary to DecimalBeginner
- Find the Largest Binary NumberIntermediate
- Add on a Fixed-Size DeviceIntermediate