Bytesize CS

Bit masking

Score 0 / 0 Streak 0 Best 0

How bit masks work

A mask is a binary number that is combined with another number, bit by bit, using a Boolean operation. Each column is worked out on its own.

ABA AND BA OR BA XOR B
00000
01011
10011
11110
  1. AND to clear bits or keep only some bits: a 0 in the mask makes the bit 0, a 1 in the mask keeps the bit as it was.
  2. OR to set bits: a 1 in the mask makes the bit 1, a 0 in the mask keeps the bit as it was.
  3. XOR to flip (toggle) bits: a 1 in the mask flips the bit, a 0 in the mask keeps the bit as it was.

For example, to check whether the bit worth 8 is on, AND the number with Binary 0000 1000. The result is 0 if the bit is off.