PHP Software Engineering

What is a bitmask?

Saw stuff like error_reporting(E_ERROR | E_WARNING | E_PARSE); or heard about bitmasks and got confused how it actually works? To my shame I never looked it up in like 12 years of programming until now.

What it actually is, is a quite efficient way to define for example grants for a user or which features are enabled for an application. It’s also quite old school but often seen and still in use.

At this point I’d suggest you to also open the PHP documentation where they explain all existing bitwise operators. I created some examples here to make it easier to understand and to visualise what is happening.

So what we’ve learned:

  • We have a 4 bits and we assign a meaning to each of them
  • We can individually switch single bits to express a state
  • Bitwise operations are supposed to be very fast and efficient
  • Use only numbers with a power of 2, otherwise we would mess up the bitmask because the binary system represent a number which is not of the power of 2 by two or more bits
  • Using a bitmask for a simple ACL system and putting each grant into a const might even make it readable and easy to work with

Would I use it? Maybe or maybe not it really depends on what I exactly need. It’s fast and solid when done right but will become messy when it’s getting much more complex. But in case you run into legacy code as I did this might help you to understand it.

Leave a Reply

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

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close