Re: bit wise math? Is there a function to easily return the bits?

From: Date: Thu, 25 Jan 2007 23:29:30 +0000
Subject: Re: bit wise math? Is there a function to easily return the bits?
References: 1 2  Groups: php.general 
Request: Send a blank email to php-general+get-247798@lists.php.net to get a copy of this message
On Thu, January 25, 2007 1:34 pm, Jon Anderson wrote: > function bits($num) { > $bit_array = str_split(strrev(decbin(intval($num)))); > $val_array = array(); > foreach ($bit_array as $pow => $bit) { > if ($val = $bit * pow(2,$pow)) > $val_array[] = $val; > } > return($val_array); > } > > (I wanted to see if I could write it in few LOC.) I wonder if there's > a > faster way... //these might be marginally faster... function bits($num){ $bits = array(); $bin = decbin(intval($num)); $v = 1; for ($b = strlen($bin) - 1; $b >= 0; $b--){ if ($bin[$b] === '1') $bits[] = $v; $v = $v * 2; } return $bits; } function bits($num){ $num = (int) $num; $v = 1; $bits = array(); while ($v <= $num){ if ($v & $num) $bits[] = $v; $v = $v * 2; } return $bits; } I suspect there is a much faster way, somewhere, somehow... > > jon > > blackwater dev wrote: >> Is there a php function I can call to pass in a number and get the >> values >> returned? >> >> For example, pass in 7 and get 1,2,4 ? >> >> Thanks! >> > > -- > PHP General Mailing List (http://www.php.net/) > To unsubscribe, visit: http://www.php.net/unsub.php > > -- Some people have a "gift" link here. Know what I want? I want you to buy a CD from some starving artist. http://cdbaby.com/browse/from/lynch Yeah, I get a buck. So?

« previous php.general (#247798) next »