I'm not familiar with bitwise operators, but I have seem them used to store simple settings before.
I need to pass several on/off options to a function, and I'd like to use a single integer for this. How can I go about setting and reading these options?
It works pretty much the same way in both languages, a side by side comparison:
C:
PHP:
Note, you don't absolutely need to use constants, I just use them out of habit. Both examples will run, I compiled the C version via
gcc -Wall flags.c -o flags
. Changeflags
in either example to anything butFLAG_TWO
orFLAG_ALL
and (sadly) no waffles will be made.In the C version, you don't have to tickle the preprocessor, it could quite easily be an enum, etc - that's an exercise for the reader.
You sure can do it in PHP.
Let's say you have four booleans you want to store in a single value. That means we need four bits of storage space
Each bit, when set individually, has a unique representation in decimal
A common way to implement this is with bit masks to represent each option. PHP's error levels are done this way, for example.
Then when you have an integer that represents 0 or more of these flags, you check with with the bitwise and operator which is
&
This operator works as such: only bits that are set in both operands are set in the result
If we checked it against
OPT_2
, then the result would look like thisquote "the idea is not good, really. you would better pass few boolean. if you want use bitwise then
"
What you have done would be okay if you were checking for a single value, although not optimal, so checking that a bit is enabled, but lets say we wanted to be able to match any, or exact we could have the following methods
if you then wanted to expand upon this by having specific actions only happening if bit x,y,z was enabled then you could use the following
I also think if you are doing what was done in the above quote, flags may not be the best idea, exact values might be better, which does have the benefit of allowing more discreet actions. (0-255) for 8-bit over 8 distinct flags
The whole reason flags work so well is because in base 2 "8" does not contain "4", and "2" does not contain "1".