Bitwise operators

 
/**
 * Bitwise operators allow us to perform operation on binary (bit-level) 
 * representation of integers.
 * 
 * Each integer is stored in binary (a sequence of bits - 0s and 1s), and
 * bitwise operations move those bits directly.
 * 
 * A bit is a representation of 1 or 0.
 * A byte is made up of 8 bits.
 * 
 * Negative numbers are stored as the bitwise NOT of the number, plus 1.
 */

$a = 6;  // 110 (binary) OR 00000110
$b = 3;  // 011 (binary)

echo $a & $b;  // Bitwise AND = 010 (binary), 2 (decimal)
echo $a | $b;  // Bitwise OR = 111 (binary), 7 (decimal)
echo $a ^ $b;  // Bitwise XOR = 101 (binary), 5 (decimal)
echo ~$a;      // Bitwise NOT = 11111001 (binary), -7 (decimal)
echo $a << 1;  // Left SHIFT = 1100 (binary), 12 (decimal)
echo $a >> 1;  // Right SHIFT = 011 (binary), 3 (decimal)

User permissions

 
/**
 * Bitwise example to manage user permissions.
 * Each permission uses a unique bit so we can easily combine them.
 */

// Define bitwise constants
define('READ', 1);    // 001 in binary
define('WRITE', 2);   // 010 in binary
define('EXECUTE', 4); // 100 in binary

// Retrive user permissions
$userPermissions = READ | WRITE;  // 001 | 010 = 001 (decimal 3)

// Check permissions
if ($userPermissions & READ) {
    echo "User can READ\n";
}
if ($userPermissions & WRITE) {
    echo "User can WRITE\n";
}
if ($userPermissions & ~EXECUTE) {
    echo "User cannot EXECUTE\n";
}

/**
 * User can READ
 * User can WRITE
 * User cannot EXECUTE
 */






Questions and answers:
Clink on Option to Answer




1. How do you write $a and $b (bitwise)?

  • a) $a && $b
  • b) $a & $b

2. Which one is the bitwise operator for OR?

  • a) |
  • b) ^

3. How do you get bits that are not in both?

  • a) $a !& $b
  • b) $a ^ $b

4. How do you change permissions from 001 to 010?

  • a) $a << 1
  • b) $a >> 1


References: