Drill

ProblemsGo › patterns

Write the field out in binary

easypatternsBit manipulationStringsGo

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

Go 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

func toBinary(flags int) string {
	
}

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 Go
func toBinary(flags int) string {
	if flags == 0 {
	    return "0"
	}
	digits := []rune{}
	field := flags
	for field > 0 {
	    digits = append([]rune{rune('0' + field&1)}, digits...)
	    field >>= 1
	}
	return string(digits)
}

The same problem in another language

More patterns problems in Go