PHP Function flags as parameters -


can explain how works? lot :)

    define("flag_a", 1);     define("flag_b", 2);     define("flag_c", 4);     function test_flags($flags=false) {         if ($flags & flag_a) echo "a";         if ($flags & flag_b) echo "b";         if ($flags & flag_c) echo "c";     }     test_flags(flag_a|flag_b); 

this done using called bitwise math. specifically, using & (bitwise and) operation check see if value set. sake of argument here, use 4-bit numbers, keep short , simple.

the number 7, in 4-bit binary, follows:

0111 

each digit has value doubled each time, , of them added make total number of 7. broken down, works so:

0    1    1    1 ^    ^    ^    ^ |    |    |    | 8    4    2    1 

so, essentially, is:

0 * 8 + 1 * 4 + 1 * 2 + 1 * 1 = 7 

now, bitwise math, bitwise and, can care bits in columns -- basically, bit in each column must 1, or set zero. so, checking '4' inside '7' bitwise math:

  0111 (7) & 0100 (4) ______   0100 (4) 

since value non-zero, true, , can determine value 4 inside value 7. consider number 11:

1    0    1    1 ^    ^    ^    ^ |    |    |    | 8    4    2    1  1 * 8 + 0 * 4 + 1 * 2 + 1 * 1 = 11 

try looking 4 in that

  1011 (11) & 0100 (4) ______   0000 (0) 

since has value of 0, false, , can consider number (4) not inside number 11.

similarly, can conclude numbers 4, 2, , 1, not 8, in 7. in 11, have 8, 2, , 1. treating numbers series of bits, instead of singular value, can store many flags inside single integer.

definitely more reading on bitwise math, can useful when used correctly, don't try shoe-horn everything.


Comments

Popular posts from this blog

java - Intellij Synchronizing output directories .. -

git - Initial Commit: "fatal: could not create leading directories of ..." -