Member-only story

How to use bitmasks in PHP

Or other languages. It’s the same concept.

Bobby Jack
CodeX

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:

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

CodeX
CodeX

Published in CodeX

Everything connected with Tech & Code. Follow to join our 1M+ monthly readers

Bobby Jack
Bobby Jack

Written by Bobby Jack

Bobby has worked as a writer and editor for publications including tech site makeuseof.com and gaming magazine Switch Player. More @ bobbyjack.me

Responses (1)

What are your thoughts?