Search code examples
phpbit-manipulation

What is the correct way to check if bit field is turn on in php


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)


Solution

  • 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)