Base
Everyday numbering system is BASE 10
// BASE 10
4768 = 4000 + 700 + 60 + 8
4 * 10 * 10 * 10 + // 4768
7 * 10 * 10 +
6 * 10 +
8
// BASE 2
45 = 32 + 8 + 4 + 1
0 * 2 * 2 * 2 * 2 * 2 * 2 * 2 + // 00101101
0 * 2 * 2 * 2 * 2 * 2 * 2 +
1 * 2 * 2 * 2 * 2 * 2 +
0 * 2 * 2 * 2 * 2 +
1 * 2 * 2 * 2 +
1 * 2 * 2 +
0 * 2 +
1
Byte
A bit is a representation of 1 or 0 / A byte is made up of 8 bits.
// highest value of a byte is 255
1 + 2 + 4 + 8 + 16 + 32 + 64 + 128 = 255 // 11111111
AND
Bits that are set in both $a and $b are set
/**
* Bitwise AND
*
* Bits set in both $a and $b
*/
$a = 9; // 8 + 1; 00001001
$b = 10; // 8 + 2; 00001010
echo $a & $b; // 8
$a = 36; // 32 + 4; 00100100
$b = 103; // 64 + 32 + 4 + 2 + 1; 01100111
echo $a & $b; // 36
OR
Bits that are set in either $a or $b are set
/**
* Bitwise OR
*
* Bits set either in $a or $b
*/
$a = 9; // 8 + 1; 00001001
$b = 10; // 8 + 2; 00001010
echo $a | $b; // 11
NOT BOTH
Bits that are set in $a or $b but not both are set.
/**
* Bitwise NOT BOTH
*
* Bits set in $a or $b but not in both
*/
$a = 9; // 8 + 1; 00001001
$b = 10; // 8 + 2; 00001010
echo $a ^ $b; // 3
NOT
The NOT operator wants to know what is set in $a but NOT set in $b
/**
* Bitwise NOT
*
* Bits set in $a but not in $b
*/
$a = 9; // 8 + 1; 00001001
$b = 10; // 8 + 2; 00001010
echo $a & ~$b; // 1
$a = 9; // 8 + 1; 00001001
$b = 10; // 8 + 2; 00001010
echo ~$a & $b; // 2
Shift
Shift the bits of $a $b steps
/**
* Bitwise SHIFT
*
* Shift bits of $a $n steps.
*
* It rovides an easy (and very fast) way of ...
* multiplying integers by a power of two.
*/
// Left
$a = 16; // 00010000
echo $a << 2; // 01000000 = 64
// Right
$a = 16; // 00010000
echo $a >> 2; // 00000100 = 4
// Multipy
$a = 1; // 00000001
echo $a << 2; // 00000100 = 4
// Demultiply
$a = 8; // 00001000
echo $a >> 2; // 00000010 = 2
Last update: 357 days ago