Bitwise Operators

April 27th, 2011

An integer stored in computer memory is comprised of bits. The number of bits in an integer varies by computer platform and possibly programming language. Integers are stored in computer memory using the binary number system. Let’s suppose a hypothetical integer has 8 bits, as shown below.

Starting on the right (the least significant bit), is 20 which equals 1. Each succeeding bit increments the exponent, 21,22,23,… .  To convert a binary number to decimal add the values associated with every bit that has the value of 1.  In the example above add 20+22+24 which evaluates to  1 + 4 + 16  which equals 21.

Two in binary is simply ‘10’. As shown below, the second bit, which represents 2, is set to one.  To store a number such as five, one must set both the first and third bits, 1 and 4 respectively which sums to the number 5.

These bits in a binary number could be used to represent a number of different types of data. One might be a set of Boolean variables.  We could have one bit indicate that spell check should be enabled, another bit could represent that the export file function should be enabled, and so on.

We could set the settings variable to 2 if we wanted to indicate that the file export feature should be enabled.  If we set the settings variable to 5 we could indicate that both the spell check and advertisements should be enabled.  If we wanted to set or clear a certain bit we could set the value of the variable as done above or we could use the bitwise OR operator to set a bit.

Above we bitwise OR 5 and 2 together, with a result of 7.  Bitwise OR works in a way similar to logical OR, in that if either bit is set then the bit in the result will be set.  If we wanted to enable file exporting, without impacting the other bits in the variable we could bitwise OR settings and 2.  The bitwise OR operator in most languages is the pipe character, not to be confused with the double pipe ‘||’ logical OR.

$settings = $settings | 2;  //Enable file exporting

To make life easier we might define constants so that we do not have to remember the number and meaning associated with each bit.

define(“SPELLCHECK”,1);
define(“EXPORT”, 2);
define(“ADS”, 4);
define(“IMPORT”,16);
$settings = $settings | EXPORT;

To determine if a bit is set we can use bitwise AND.  When we use bitwise AND the result will either be zero, meaning that the bit is not set or the result will be non-zero meaning that the bit is set.

Above, we AND 7 and 2 we get a result of two because both bits must be set in order for the corresponding bit in the result to be set.  That means that the file export feature is enabled.

In another example, we AND 7 and 8, notice how the result is 0, this is because the 4th bit, file import is not enabled.  The bitwise AND operating is the single ‘&’.

if($settings & IMPORT == 0){
     //This bit is not set.
}else{
     //The bit is set.
}