What Are Bitmasks and Bitwise Operators?
Part 1 of a serialized version of Bitmasks for Fun and Profit: Practical Applications for Web Developers
Bitmasks and bitwise operators are used in computer science to manage and manipulate data at the most basic level—bits. Each bit in a bitmask represents a binary state (on or off, 1 or 0). In web development, bitmasks allow for compact data storage, simpler data relations, reduced memory usage, and faster data processing. Developers can quickly check or change multiple conditions by reading the bits of an integer.
Bitmasks Work Like Light Switches:
Imagine you have a row of light switches in your room. Each switch can be ON (1) or OFF (0). Each switch controls a different light independently.
You can track which lights are on or off by noting the switch positions. A bitmask lets you store all switch positions in a single unique number.
Bitmasks can store and recall switch positions as presets.
Bitwise operators can turn switches on and off and evaluate their current positions.
When you have a group of bitmasks, you can compare, sort and filter them using bitwise operators.
Example: Four Switches (Bits)
Four bits can store 16 unique positions. Since zero is the first, 15 will be the last.
Bitmask (Binary) Description Decimal Value
0000 All lights are off. 0
0001 Only the first light is on. 1
1000 Only the fourth light is on. 8
0011 The first and second lights are on. 3
0101 The first and third lights are on. 5
1111 All lights are on. 15
```⬤
In a 32-bit integer, you can store up to 32 switches. In a 64-bit integer, you can store 64 switches. These are binary numbers that can be represented as a decimal integer. If you need more switches, you can store them as a set or array, but then you lose the ability to use bitwise operations. You can store an unlimited number of unique bits in a set.
Bitwise operators:
AND &
OR |
XOR ^
NOT ~
LEFT SHIFT <<
RIGHT SHIFT >>
Bitwise operators are mathematical operators that act on binary numbers. They are similar to addition, subtraction, multiplication, and division but work in binary math directly on bits. Bitwise operators make bitmasks possible by setting, clearing, toggling, manipulating, and checking bits. Comparison operators make bit identification extremely fast, sometimes in a single CPU instruction.
If the light switches were set to 0101
(5) and you needed to change them to 1111
(15), you would simply turn on the second and fourth switches. Just as you would compare the two positions to find the differences and use your hand to flip the switches, computers use bitwise operators to find the differences and turn specific bits on or off in a bitmask.
We go over these operators in detail throughout this series.
This is part 1 of a serialized version of my book:
Bitmasks for Fun and Profit: Practical Applications for Web Developers
I publish several books about Guitar, Music and Programming on my Author Page on Amazon:
Follow me at Torus Head Studios!