https://www.php.net/manual/en/language.operators.bitwise.php
https://www.w3schools.com/js/js_bitwise.asp
$a & $b | And | Bits that are set in both $a and $b are set. |
$a | $b | Or (inclusive or) | Bits that are set in either $a or $b are set. |
$a ^ $b | Xor (exclusive or) | Bits that are set in $a or $b but not both are set. |
~ $a | Not | Bits that are set in $a are not set, and vice versa. |
$a << $b | Shift left | Shift the bits of $a $b steps to the left (each step means "multiply by two") |
$a >> $b | Shift right | Shift 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)
| Operation | Result | Same as | Result |
|---|
| 5 & 1 | 1 | 0101 & 0001 | 0001 | | 5 | 1 | 5 | 0101 | 0001 | 0101 | | ~ 5 | 10 | ~0101 | 1010 | | 5 << 1 | 10 | 0101 << 1 | 1010 | | 5 ^ 1 | 4 | 0101 ^ 0001 | 0100 | | 5 >> 1 | 2 | 0101 >> 1 | 0010 | | 5 >>> 1 | 2 | 0101 >>> 1 | 0010 |
| | | |
<?php
function countSetBits($n)
{
$count = 0;
while ($n)
{
$count += $n & 1;
$n >>= 1;
}
return $count;
}
$i = 9;
echo countSetBits($i);
?>
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