# Math & Number Handling in PHP – The ABCs of PHP Part 6 Page 2

By PHP Builder Staff
on April 21, 2009

Number Shifting
PHP also has a useful operator known as a barrel shifter.
The barrel shifter or Logical shift as some people may call
it is represented by the << and >> (Chevron)
operators.
When applied to a given number, the number is shifted one
bit position in that direction. If the idea of shifting
seems a little alien then it helps to think of this in terms
of binary, and if binary is a little strange, then lets have
a little recap first.
Binary what on earth is that?
Human beings are taught at school to deal with the decimal
system, in doing this we are taught that numbers start at 0
and go towards 9, once 9 is reached we move across to the
next column and continue counting.
The columns are labelled as Hundreds, Tens and Units.
Binary numbers are not much different, except that they only
go from 0 to 1 before moving across a column.
This for a computer is an absolutely perfect state of
affairs, as deep down at the very basic level in a computer,
all there is to represent numbers are a series of on or off
electrical pulses. Unfortunately this is not so easy for
humans to understand, so in order to make it easy to
understand we label across the columns in powers of 2 as
follows.
```	---------------------------------------
| 128 | 64 | 32 | 16 | 8 | 4 | 2 | 1 |
---------------------------------------
```
As you can see above, there are 8 columns. When a number is
referred to as an 8 bit number, then it is meant that there
are 8 columns across the top, a 16 bit number would continue
on from 128 to 256, then 512, 1024 and so on multiplying by
2 each time.
If we then put a binary number under the columns, EG:
```	---------------------------------------
| 128 | 64 | 32 | 16 | 8 | 4 | 2 | 1 |
---------------------------------------
|  0  |  0 |  1 |  0 | 0 | 1 | 0 | 1 |
---------------------------------------
```
You can see where the ‘1’ values lie under the columns, if
we add the columns together from right to left, which in
this case is 1 + 4 + 32 or 37 so 00100101 = 37 in decimal.
To convert back the other way, we simply keep subtracting
the largest value we are able to from right to left while
still keeping a positive whole number, so
• 37 – 128 Not possible
• 37 – 64 Not Possible
• 37 – 32 Leaves 5
• 5 – 16 Not possible
• 5 – 8 Not possible
• 5 – 4 Leaves 1
• 1 – 2 Not possible
• 1 – 1 Leaves 0 (All done, no numbers left)
So now we’ve had a quick recap on binary (I’m not going into
it any deeper as this is not a lesson on using binary) why
is the barrel shifter so important?

﻿