Re: bit wise math? Is there a function to easily return the bits?
| From: | Paul Novitski | Date: | Thu, 25 Jan 2007 23:22:21 +0000 |
| Subject: | Re: bit wise math? Is there a function to easily return the bits? | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-247797@lists.php.net to get a copy of this message | ||
At 1/25/2007 11:16 AM, 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 ?Here's a slightly more off-the-wall contribution: ==================================== function bin2array($iDecimal) {
$aResult = array_reverse(explode("\r\n", chunk_split (decbin($iDecimal), 1)));
array_walk($aResult, 'doPower');
return $aResult;} function doPower(&$iValue, $iIndex) {
$iValue = $iValue * pow(2, $iIndex);} ==================================== Here's the break-down of that eye-crossing first statement: array_reverse(explode("\r\n", trim(chunk_split (decbin($iDecimal), 1)))); using $iDecimal = 6: $a = decbin($iDecimal) --> '110' $b = chunk_split($a, 1) --> '1\r\n1\r\n0'
$c = explode("\r\n", $b); // array(1,1,0)
$d = array_reverse($c); // array(0,1,1)
(If you're using PHP5 you can use split() instead of chunk_split() and explode().)
The doPower function performs this transform on each member of the array:
$iValue = $iValue * pow(2, $iIndex);
Ix Val Math 0 0 0 * 2^0 = 0 1 1 1 * 2^1 = 2 2 1 1 * 2^2 = 4Regards, Paul __________________________ Juniper Webcraft Ltd. http://juniperwebcraft.com