问题
What is the correct way to check if bit field is turn on - (in php) ?
I want to check a bit field that come from db(mysql) if is turn on or not.
is this is the correct way ?
if($bit & 1)
Are there other ways ?
I see somebody code that using ord() function , it is correct ?
like if(ord($bit) == 1)
回答1:
Use
if( $bit & (1 << $n) ) {
// do something
}
Where $n is the n-th bit to get minus one (for instance, $n=0 to get the least significant bit)
回答2:
It's a bit late but might be usefull for future visitors to this question. I've made myself a little function that returns all bits that are active in a certain flag.
/**
* Shows all active bits
*
* @param int $flag
* @return array
*/
function bits($flag)
{
$setBits = array();
for ($i = 1; $i <= 32; $i++) {
if ($flag & (1 << $i)) {
$setBits[] = (1 << $i);
}
}
// Sort array to order the bits
sort($setBits);
return $setBits;
}
echo "<pre>";
var_dump(bits(63));
echo "</pre>";
回答3:
I use
if (($flag & 0b010) == 0b010) {
// here we know that the second bit (dec 2) is set in $flag
}
回答4:
Yes, if($bit & 1) is the correct way to check, according to the PHP manual.
An alternative could be to do the check in your MySQL query.
回答5:
To get the correct bit, use this syntax:
$bit & (1 << $n)
Where $n is to get the (n+1)-th least significant bit. So $n=0 will get you the first least significant bit.
来源:https://stackoverflow.com/questions/3511709/what-is-the-correct-way-to-check-if-bit-field-is-turn-on-in-php