Re: Test for one bit set?

From: Date: Sun, 07 Apr 2002 22:29:19 +0000
Subject: Re: Test for one bit set?
References: 1 2  Groups: php.general 
Request: Send a blank email to php-general+get-91956@lists.php.net to get a copy of this message
Thanks to all those that replied. Especially Torben. (What have you been up to?) Miguel's solution works great. Check out the example below: <?php function isOneBitSet($n) { $x = log($n)/log(2); return ($x == intval($x)); } for ($i = 0; $i < 32769; ++$i) { if(isOneBitSet($i)) { print("$i, "); } } ?> Prints out: 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, Just what I wanted. Thanks again, Charlie > > 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 >

« previous php.general (#91956) next »