Binary to Decimal
Beginner · Write the code · from Binary Numbers and Bits: How Computers Represent Data
From the lesson: How do you convert binary to decimal?
Multiply each bit by its place value and add up the results. Since every bit is 0 or 1, that is the same as adding the place values that have a 1 under them. The program below does it one position at a time, starting from the rightmost bit.
Read this part of the lessonWrite to_decimal(bits). It takes a binary number as a string of 0 and 1 characters and returns its decimal value as an integer. Work it out with place values instead of calling int(bits, 2), which would do the whole job for you.
to_decimal('1101') -> 13
to_decimal('0') -> 0def to_decimal(bits):
# Add up bit x place value for every position
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_decimal("1101")) | 13 |
| print(to_decimal("11111111")) | 255 |
| print(to_decimal("0")) | 0 |
More Binary Numbers exercises
- Decimal to BinaryIntermediate
- Find the Largest Binary NumberIntermediate
- Add on a Fixed-Size DeviceIntermediate