Write the field out in binary
A diagnostics screen prints a flags field as ones and zeros so an engineer can see at a glance which switches are on.
- Return the binary digits, most significant first.
- No leading zeros — except zero itself, which is written "0".
- The value is never negative.
to_binary(flags: int) → string
Where you start
def to_binary(flags: int) -> str:
Worked examples
| Call | Result |
|---|---|
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