Bit-wise operations have a variety of handy uses, one of the best ones is being able to store multiple values or flags within one variable.
For instance, say you want to store whether something can go in a number of directions. You could create 4 seperate variables for each direction - left, right, up, down and set them to 1 or 0 depending on the available directions - or a simpler method would be to have one variable with bits set to reflect the same directions.
Using the bit value method is also very useful in database applications. Instead of having to modify the table and add new columns when a new direction or object is created, you simply use an unused bit value.
The limit for this method is the size of the variable you are performing the operations on. For a 32 bit variable you can have 32 unique values - and 4294967295 possible combinations! Each of the 32 values is raised to the power of 2. 1,2,4,8,16,32,64 and so on.
An easy way to display bit values in PHP code is to use a hexidecimal format. When coding, this method also make is easier to calculate the next available number:
$a = 0x00000001 \\ 1
$b = 0x00000002 \\ 2
$c = 0x00000004 \\ 4
$d = 0x00000008 \\ 8
$e = 0x00000010 \\ 16
$f = 0x00000020 \\ 32
$g = 0x00000040 \\ 64
$h = 0x00000080 \\ 128
$i = 0x00000100 \\ 256
and so on .. the pattern becomes obvious after a while. To set bits use the bit wise OR operator ( | ). To check whether a bit is set use the bit wise AND ( & ) operator.
The example listed below provides a simple mechanism for setting a variable with multiple bit values, and then displaying which bits are set from the same variable. Instead of directions, we are using web server capabilities. |