# Bitwise Operations in PHP

Bitwise operations can be pretty useful, especially for things like flags. Unfortunately, many PHP developers don't realise the power of Bitwise operations.

So, here's a handy little guide.

There are 6 standard Bitwise operations. They allow for the "manipulation of specific bits of an integer". They are:

```
AND ( & )
OR ( | )
XOR ( ^ )
NOT ( ~ )
Shift Left ( << )
Shift Right ( >> )
```

## Examples

I've written a simple example (following unix file permissions):

```
define('EXECUTE_PERMISSION', 0b1); // 0b1 = binary 1 = 1
define('WRITE_PERMISSION', 0b10); // 0b10 = binary 10 = 2
define('READ_PERMISSION', 0b100); // 0b100 = binary 100 = 4
$permission = 0b110; // WRITE_PERMISSION | READ_PERMISSION = 0110
$canWrite = (bool)($permission & WRITE_PERMISSION); // TRUE
// 0110 AND 0010 = 0010 = 2. In PHP anything greater than 0 is true.
$canExecute = (bool)($permission & EXECUTE_PERMISSION); // FALSE
// 0110 AND 0001 = 0000 = 0. In PHP, 0 is false.
```

And another example for colours for colours:

```
$color = 0x99FFCC; // hex colour
// $color in binary is 1001 1001 1111 1111 1100 1100
$red = $color >> 16; // Red now contains 0x99 = 153
// Shifts the last 16 bits off, so we get 1001 1001 (first 8 bits)
$green = ($color & 0x00FF00) >> 8; // Green now contains 0xFF = 255
// Performs AND, result: 0000 0000 1111 1111 0000 0000
// Then shits the last 8 bits away, resulting in 0000 0000 1111 1111. Removing the leading 0's leaves 1111 1111.
$blue = $color & 0x0000FF; // Blue now contains 0xCC = 204
// Performs AND, result: 0000 0000 0000 0000 1100 1100 = 204
```

## What happens in Binary

AND (&)

```
0110 & 0101
0 & 0 is 0
1 & 1 is 1
1 & 0 is 0
0 & 1 is 0
Result: 0100
```

OR (|)

```
0110 | 0101
0 | 0 is 0
1 | 1 is 1
1 | 0 is 1
0 | 1 is 1
Result: 0111
```

XOR (^)

```
0110 ^ 0101
0 ^ 0 is 0
1 ^ 1 is 0
1 ^ 0 is 1
0 ^ 1 is 1
Result: 0011
```

NOT (~)

```
~0110
~ 0 = 1
~ 1 = 0
~ 1 = 0
~ 0 = 1
Result: 1001
Note. PHP doesn't use 4 bit integers. The actual result would be something like (on 32bit machines):
1111 1111 1111 1111 1111 1111 1111 1001
```

Shift Left (<<)

```
0110 0101 << 4 = 0101 0000 (everything is moved 4 to the left)
Note PHP doesn't use 8 bit integers either, the actual result would be something like (on 32bit machines):
0000 0000 0000 0000 0000 0110 0101 0000
```

Shift Right (>>)

```
0110 0101 >> 4 = 0000 0110 (everything is moved 4 to the right)
We can ignore the leading zeroes...
A shift left could be said to be a multiplier of 2, and a shift right a divisor of 2.
```

## Further Reading

You can read more here: Bitwise Operators (warning: it gets very in-depth).

Written by

**Kieran**on 2019-04-19