Drill

ProblemsJavaScript › patterns

Write the field out in binary

easypatternsBit manipulationStringsJavaScript

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

Solve it in the editor →

Where you start

function toBinary(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 JavaScript
function toBinary(flags) {
  if (flags === 0) return "0";
  let digits = "";
  let field = flags;
  while (field > 0) {
    digits = String(field & 1) + digits;
    field >>= 1;
  }
  return digits;
}

The same problem in another language

More patterns problems in JavaScript