Bit Twiddler — Data Structures

Write bitwise expressions that turn the input into the target in every test case: 18 levels of masks, shifts and set, clear and toggle.

What you learn in this game

Every house in Gang Sawo has eight lamps under its eaves, one bit per lamp: lamp 7 on the left, lamp 0 on the right. Lamp k is worth 2 to the power k (lamp 0 = 1, lamp 1 = 2, lamp 2 = 4, up to lamp 7 = 128), and a house's number is the sum of the lamps that are on. The OR operator (|) turns on the lamps wherever the mask is 1; the other lamps are untouched. One switch serves every house, so a fixed number will not fit them all.

To turn a lamp off, use AND (&) with the mask flipped. ~ (NOT) flips all 32 bits of the number, not just eight lamps: ~8 is …11110111, all 1s except bit 3, the 24 bits of the relay box included. ANDing with it forces lamp 3 off and leaves the rest, relay box too. The numbers JavaScript's bit operators work on are always 32 bits. Bit 31 is the sign: when it is on, the number is negative.

The XOR operator (^) flips bits: wherever the mask is 1, the bit is flipped (0 becomes 1, 1 becomes 0); the rest stay. It is a toggle switch: run it twice and the lamps are back as they were.

The left shift operator (<<) moves every bit left; 0s come in from the right. One step left doubles every lamp's value, so x << 3 is the same as times 8. But only while the result fits in 32 bits: bits pushed past bit 31 are lost, and a bit that lands in bit 31 makes the number negative.

A right shift moves bits to the right; the rightmost bits fall off. JavaScript has two: >> fills from the left with the sign bit (a negative number stays negative), >>> fills with 0 and reads the number as 32 unsigned bits. For positive numbers the two are the same.

Hexadecimal writes four bits as one digit: 0 to 9, then A to F for 10 to 15. Eight lamps become two digits after 0x: the left digit is the four left lamps, the right digit the four right lamps. Four bits are called a nibble.

What the levels ask

  1. One switch for every house: x is that house's lamps right now.
  2. A lamp's number is not its value: each lamp is worth twice the one on its right.
  3. Each house's relay box on its wall holds bits 8 to 31: the lamps the street cannot see.
  4. On and off are flipped by the same switch.
  5. A lamp 1 that is off stays off.
  6. A shift moves every bit at once.
  7. JavaScript has two right shifts; the houses at the end of the gang choose between them.
  8. One mask can hold more than one lamp.
  9. Four bits side by side are a nibble: one hexadecimal digit.
  10. A mask that is 1 where you want to keep.
  11. Bring it down first, then filter.
  12. hi and lo are pinned to every house's door.

And more, 18 levels in all.