Home

Bitmasks

Bitmasks are values used to encode multiple Boolean flags within a single binary quantity, typically an integer. Each bit position in the mask represents a separate condition or option, which allows compact storage and fast manipulation of large sets of binary states.

Common operations rely on bitwise operators. To turn on a flag, you OR the value with a

Mask creation and composition: a single-bit mask is produced by shifting 1 left by k positions, such

Common applications: storing configuration flags, feature toggles, permissions, file modes, and protocol fields. They enable fast

Notes: be mindful of integer width and sign in different languages; bit shifts may have different semantics;

mask:
value
=
value
|
mask.
To
turn
off,
AND
with
the
complement:
value
=
value
&
~mask.
To
toggle,
use
XOR:
value
=
value
^
mask.
To
check,
test
with
AND:
if
(value
&
mask)
!=
0
then
the
flag
is
set.
as
mask
=
1
<<
k.
Multi-flag
masks
combine
via
OR:
maskA
|
maskB.
You
can
also
express
ranges
of
bits
with
shifts,
and
use
masks
to
clear
or
clear
ranges.
checks
and
minimal
memory
usage,
and
are
widely
supported
across
languages.
In
some
systems,
bitmasks
are
used
for
bitfields
in
structs.
use
named
constants;
prefer
explicit
masks
for
readability.
Debugging
tip:
isolate
masking
operations
and
test
with
representative
values.