Drill

ProblemsPython › patterns

Write the field out in binary

easypatternsBit manipulationStringsPython

A diagnostics screen prints a flags field as ones and zeros so an engineer can see at a glance which switches are on.

to_binary(flags: int) → string

Solve it in the editor →

Where you start

def to_binary(flags: int) -> str:
    

Worked examples

CallResult
to_binary(5)"101"
to_binary(0)"0"
to_binary(1)"1"
to_binary(8)"1000"

Hint

Peel off the lowest bit with a mask, shift down, and repeat. The digits come out backwards, so reverse them at the end.

Reference solution in Python
def to_binary(flags: int) -> str:
    if flags == 0:
        return "0"
    digits = ""
    field = flags
    while field > 0:
        digits = str(field & 1) + digits
        field >>= 1
    return digits

The same problem in another language

More patterns problems in Python