PROGRAMMING

 
REMEMBERS




Last update:   29-10-2021

Concept

Base

Everyday numbering system is BASE 10. The BASE 2 system has the same concept.
 
4768 = 4000 + 700 + 60 + 8 =

4 * 10 * 10 * 10 + 
    7 *  10 * 10 + 
      6 * 10 +
           8
 
45 = 32 + 8 + 4 + 1 = 

// 00101101
0 * 2 * 2 * 2 * 2 * 2 * 2 * 2 + 
    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
... 5 lines
 

Byte

A bit is a representation of 1 or 0. A byte is made up of 8 bits. The highest value of a byte is 255, (every bit is set).
 
1 + 2 + 4 + 8 + 16 + 32 + 64 + 128 = 255 // 11111111
Operators    (2/3)

Operators

AND

Bits that are set in both $a and $b are set
 
$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
... 1 lines
 

OR

Bits that are set in either $a or $b are set
 
$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.
 
$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
 
$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
... 1 lines
 

Shift

Shift the bits of $a $b steps
 
$a = 16; // 00010000
echo $a << 2; // 01000000 = 64

$a = 16; // 00010000
echo $a >> 2; // 00000100 = 4
It rovides an easy (and very fast) way of multiplying integers by a power of two.
 
$a = 1; // 00000001
echo $a << 2; // 00000100 = 4

$a = 8; // 00001000
echo $a >> 2; // 00000010 = 2
Overflow and underflow scenarios that can yield unexpected results. For example, on a 32-bit machine, the following will happen:
 
$a = 1; // 00000001

echo $a << 8; // 10000000 = 256
echo $a * pow(2, 8); // 256

$a = 1; // 00000001

echo $a << 64; // 0
       // all the bits have been shifted out of the integer value
echo $a * pow(2, 64); // 4294967296
... 2 lines
 
Task

 
/**
 * Given the users $role and access $rights ...
 * Check if Mike has admin rights and downgrade him
 * The wrong approach will be:
 *  if ($is_admin && $can_edit_articles ...
 */

 $rights = (object) ["read"=>1, "write"=>2, "readwrite"=>16, "admin"=> 32];
 $role   = (object) ["jim"=>96, "mike"=>32];

...

solution code
Questions    
String

        A B C D E F
🔔
1/6