Friday, 26 February 2021

bit wise operator in PHP and JS, USAGE in DB

 

https://www.php.net/manual/en/language.operators.bitwise.php
https://www.w3schools.com/js/js_bitwise.asp

$a & $bAndBits that are set in both $a and $b are set.
$a | $bOr (inclusive or)Bits that are set in either $a or $b are set.
$a ^ $bXor (exclusive or)Bits that are set in $a or $b but not both are set.
~ $aNotBits that are set in $a are not set, and vice versa.
$a << $bShift leftShift the bits of $a $b steps to the left (each step means "multiply by two")
$a >> $bShift rightShift the bits of $a $b steps to the right (each step means "divide by two")


5 >> 1, move 1 over to left bit (divide by 2)
5 >> 2, move 2 over to left bit(dived by 4)

OperationResultSame asResult
5 & 110101 & 0001 0001
5 | 150101 | 0001 0101
~ 510 ~0101 1010
5 << 1100101 << 1 1010
5 ^ 140101 ^ 0001 0100
5 >> 120101 >> 1 0010
5 >>> 120101 >>> 1 0010
<?php
// PHP program to Count set
// bits in an integer
 
// Function to get no of set 
// bits in binary representation
// of positive integer n
function countSetBits($n)
{
    $count = 0;
    while ($n)
    {
        $count += $n & 1;
        $n >>= 1;
    }
    return $count;
}
 
// Driver Code
$i = 9;
echo countSetBits($i);
 
// This code is contributed by ajit
?>

https://www.geeksforgeeks.org/count-set-bits-in-an-integer/


x >>= 1 means "set x to itself shifted by one bit to the right". The expression evaluates to the new value of x after the shift. (x = x >> 1;)

https://stackoverflow.com/questions/38922606/what-is-x-1-and-x-1

x+=1 is more effiecent that x=x+1, as x+=1 only evaludated once

https://stackoverflow.com/questions/808062/x-x1-vs-x-1


Usage in DB
Instead of creating multiple columns in DB for flag values, just create one column called "bit" with the addition of flag values :
'bits' => array(
'flag1' => 1,
'flag2' => 2,
'flag3' => 4,
'flag4' => 8,

),

If flag1, flag2, flag3, flag4 are all turned on, just save total sum of 15 into "bits" column

and to check which flag is turned on, do bitwise operation &,
15 & flag 1 (1), should be 1(shared bit is 01), 15 & flag 2 (2) should be 2(shared bit is 10).

If not turned on & operation gives 0, 





No comments:

Post a Comment