Lazy with bitwise operators

There is a certain charm in using a single variable to store a bunch of boolean flags. Binary is convenient because it is all 1′s (true) and 0′s (false). The part I don’t like is assigning variables to each position in the binary number. When mapping out the variable, there are a couple of ways you may think of defining your flags. It would be somewhat convenient if you could write the binary numbers out like:

$is_user = 1;
$is_admin = 10;
$is_superhero = 100;
$is_troll = 10000000000000000;

PHP does not offer this convenience. Some devs might suggest hex notation (0×1, 0×2, etc) or something that makes me sad like using bindec(). Then there is the tried-and-true method of defining your variable for each position in the binary string:

$is_user = 1;
$is_admin = 2;
$is_superhero = 4;
$is_troll = 65536;

I prefer a more lazy approach (and I think it is more readable, personally) to defining my boolean flags; use the shift left operator <<

The shift left operator is basically multiplying a number times 2. Since the binary positions are powers of 2, I can define my flags like so:

$is_user = 1;
$is_admin = (1 < < 1); //2
$is_superhero = (1 << 2); //4
$is_troll = (1 << 17); //65536

I like writing it this way for a number of reasons:

    • the second number tells me which position the flag is in (starting from 0)
    • It is easy for me to tell when I’m running out of flags (you only get 32 bits per number!).
    • bitwise operations are fast

    I understand that there are many more ways I could do this (like the pow() function and others); but that would be less fun, right?
    Checking against my permission variable is easy with the & bitwise operator:

    if ($permission & $is_admin) { /* do admin stuff */ }

About Jon Trelfa

I live in Detroit, Mi.
This entry was posted in Code. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>