How to use bitmasks in PHP
Or other languages. It’s the same concept.
Bitmasks are as old as computing itself and, admittedly, were more useful in the days of memory scarcity and low-level programming. But there’s nothing to stop you using them today, when appropriate.
PHP makes use of bitmasks in many of its built-in functions. Consider:
json_encode($json, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
(my personal favourite way of calling json_encode…)
Every time you pass flags to json_encode
—or any similar function, of course—you’re making use of a bitmask.
What’s a bitmask?
A bitmask / bitfield is a series of boolean values, stored in unique bits of an individual integer. You can define related flags in such a way that you can then use them in combination, in a single numeric value.
How a bitmask works
The second argument in the call to json_encode
above is an integer, but we obtain it via bitwise logic. The pipe character (|
) performs a bitwise OR. A ‘bitwise or’ is simply a series of bits obtained by inspecting two other binary values. A 1 bit in either input results in a 1 bit in the output. For example: