<pre><?php
$n = 7;

for ($i = 1; $i< $n;$i <<=1) if ($i & $n) $a[] = $i; // put it in an array or do whatever, $i contains the parts.

var_dump($a);
?>
</pre>


----- Original Message ----- From: "Richard Lynch" <[EMAIL PROTECTED]>
To: "Jon Anderson" <[EMAIL PROTECTED]>
Cc: "blackwater dev" <[EMAIL PROTECTED]>; <php-general@lists.php.net>
Sent: Friday, January 26, 2007 12:29 AM
Subject: Re: [PHP] bit wise math? Is there a function to easily return the bits?


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?

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to