RE: [PHP] Test for one bit set?
| From: | Brinkman, Theodore | Date: | Mon, 08 Apr 2002 14:53:33 +0000 |
| Subject: | RE: [PHP] Test for one bit set? | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-92055@lists.php.net to get a copy of this message | ||
Try a bitwise and (I think the operator is '&')...
<?php
$bitMask = 16;
$value1 = 24;
$value2 = 36;
?>$value1 has bit 5 set? <?php
if($bitMask & $value1)
{
//should get here
echo 'true\r\n';
}
else
{
echo 'false\r\n';
}
?>$value2 has bit 5 set? <?php
if($bitMask & $value1)
{
echo 'true\r\n';
}
else
{
//should get here
echo 'false\r\n';
}
?>
- Theo
-----Original Message-----
From: Miguel Cruz [mailto:mnc@stoic.net]
Sent: Sunday, April 07, 2002 5:04 PM
To: Charlie Killian
Cc: php-general@lists.php.net
Subject: Re: [PHP] Test for one bit set?
On Sun, 7 Apr 2002, Charlie Killian wrote:
> How can I test if a number only has on bit set?
>
> So testing different numbers will return TRUE or FALSE:
>
> testing 00010000 would return TRUE.
> testing 00000011 would return FALSE.
Think back to math class when you were 14!
function isOneBitSet($n)
{
$x = log($n)/log(2);
return ($x == intval($x));
}
Cheesy alternative:
function isOneBitSet($n)
{
return (1 == substr_count(base_convert($n, 10, 2), '1'));
}
miguel