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

From: Date: Fri, 26 Jan 2007 08:49:11 +0000
Subject: Re: bit wise math? Is there a function to easily return the bits?
References: 1 2 3  Groups: php.general 
Request: Send a blank email to php-general+get-247811@lists.php.net to get a copy of this message
<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" <ceo@l-i-e.com> To: "Jon Anderson" <jon@gamingsolutions.ca> Cc: "blackwater dev" <blackwaterdev@gmail.com>; <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


« previous php.general (#247811) next »