Drill

ProblemsC# › patterns

Write the field out in binary

easypatternsBit manipulationStringsC#

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

ToBinary(flags: int) → string

C# needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

public string ToBinary(int flags) {
    
}

Worked examples

CallResult
ToBinary(5)"101"
ToBinary(0)"0"
ToBinary(1)"1"
ToBinary(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 C#
public string ToBinary(int flags) {
    if (flags == 0) return "0";
    var digits = new List<char>();
    int field = flags;
    while (field > 0) {
        digits.Insert(0, (char)('0' + (field & 1)));
        field >>= 1;
    }
    return new string(digits.ToArray());
}

The same problem in another language

More patterns problems in C#