Re: bit wise math? Is there a function to easily return the bits?
| From: | Satyam | Date: | Fri, 26 Jan 2007 13:30:13 +0000 |
| Subject: | Re: bit wise math? Is there a function to easily return the bits? | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-247819@lists.php.net to get a copy of this message | ||
----- Original Message ----- From: "Satyam" <Satyam@satyam.com.ar>
<pre><?php $n = 7;Sorry, the above fails for numbers which are powers of two, it should have been: for ($i = 1; $i <= $n;$i <<=1) if ($i & $n) echo "$i<br />"; (Notice less than or equal in the while part) Satyamfor ($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) {//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...$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...jon blackwater dev wrote:-- 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.phpIs 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