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

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



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 = 4

Regards,

Paul
__________________________

Juniper Webcraft Ltd.
http://juniperwebcraft.com
--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux