Sunday 5 April 2009

Bit collection from integer value

The next example of code that was appeared once without any historical bounds of it's appearance. Look. It collects all bits from an integer value into an array.
function array_bits($integer, $bit_keys=false)
{
    static $bits = array();

    $result = array();

    if ( empty($bits) ) {
        $i = 1;
        while ( $i ) {
            if ( $i & $integer ) {
                $result[] = $i;
            }

            $bits[] = $i;
            $i <<= 1;
        }
    } else {
        foreach ($bits as $i) {
            if ( $i & $integer ) {
                $result[] = $i;
            }
        }
    }

    if ( $bit_keys ) {
        $result = array_flip($result);
    }

    return $result;
}

$a = rand(0, 1000);

print "$a\n";
print_r(array_bits($a, false));
print_r(array_bits($a, true));

No comments:

Post a Comment