tags:

views:

42

answers:

3

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)

+3  A: 

This is the correct way to check, according to the PHP manual.

An alternative could be to do the check in your MySQL query.

Jasper De Bruijn
+1  A: 

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.

Gumbo
Haim Evgi
Haim Evgi
@Haim Evgi: Oh yes, of course, it’s zero-based.
Gumbo
+1  A: 

Use

if( $bit & (1 << $n) ) {
  // do something
}

Where $n is the n-th byte to get minus one (for instance, $n=0 to get the first bit)

Frxstrem