Editor

Add on a Fixed-Size Device

Intermediate · Write the code · from Binary Numbers and Bits: How Computers Represent Data

From the lesson: What happens when a number needs more bits than it has?

In many programming languages, an integer gets a fixed number of bits, such as 8, 16, 32 or 64. That limits the range of values it can hold and the math you can do with them. With 8 bits, the biggest pattern is 11111111, which is 255. The true answer to 255 + 1 is 100000000, and that needs 9 bits.

Read this part of the lesson

A sensor stores every number in a fixed number of bits and wraps around on overflow: any bits that do not fit are thrown away. Write add_fixed(a, b, num_bits) that returns the value the sensor stores after adding a and b. Both a and b already fit in num_bits bits.

add_fixed(5, 3, 4)   ->  8   (8 fits in 4 bits)
add_fixed(15, 1, 4)  ->  0   (16 needs 5 bits, so it wraps)
def add_fixed(a, b, num_bits):
# Keep only the part of the sum that fits in num_bits bits
pass

What Check runs

Your code runs first, then each of these lines, and 2 more that stay hidden. The output must match exactly.

RunsExpected output
print(add_fixed(5, 3, 4))8
print(add_fixed(15, 1, 4))0
print(add_fixed(200, 100, 8))44

More Binary Numbers exercises

All Python exercises · 50 practice problems