Frage

So I'm trying to work on a web service that deals with long bit arrays (100+ bits).

Can anyone suggest a class in PHP that deals with long bit arrays?

War es hilfreich?

Lösung

PHP doesn't support long bit arrays, you can use ordinary arrays and calculate proper offset as (this is sample for 32 bit architecture):

$array = [];
$bitToSet = 33;
setbit($array, $bitToSet);
print_r($array);

echo getbit($array, $bitToSet-1) . "\n";
echo getbit($array, $bitToSet) . "\n";
echo getbit($array, $bitToSet+2) . "\n";

function setbit(&$array, $bitNumber) {
    $arrayIdx = $bitNumber >> 5; // I suppose 32 bit int
    $bitIdx = $bitNumber & 0x1f;
    if (!isset($array[$arrayIdx])) $array[$arrayIdx] = 0;
    $array[$arrayIdx] = (1<<$bitIdx); 
}
function uRShift($a, $b) {
    if($b == 0) return $a;
    return ($a >> $b) & ~(1<<(8*PHP_INT_SIZE-1)>>($b-1));
}
function getbit(&$array, $bitNumber) {
    $arrayIdx = $bitNumber >> 5;
    $bitIdx = $bitNumber & 0x1f;
    if (!isset($array[$arrayIdx])) $array[$arrayIdx] = 0;
    return uRShift($array[$arrayIdx], $bitIdx)&1;
}

also you can check about GMP and BC Math, second not the best option anyway

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top