0

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?

Naftali
  • 144,921
  • 39
  • 244
  • 303
Tengyu Liu
  • 1,223
  • 2
  • 15
  • 36
  • 2
    Questions asking us to recommend or find a tool, library or favorite off-site resource are off-topic for Stack Overflow – Kermit Oct 30 '13 at 21:03
  • 1
    I don't think the OP is asking for an off-site resource, but rather for code (a PHP class). Could be wrong, though. – showdev Oct 30 '13 at 21:04
  • @showdev same thing... – Naftali Oct 30 '13 at 21:05
  • 1
    @Neal Not the same thing -- There's a different closing flag for questions asking for code vs. questions asking for an off-site resource. But I guess the end result is similar. – showdev Oct 30 '13 at 21:07
  • I think the OP asks for something similar to `bitset` in c++, which is really useful. And just using ordinary integers limits the bitset to 64. Don't see why is this off-topic? – PeMa Sep 15 '17 at 08:16

1 Answers1

6

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

Iłya Bursov
  • 23,342
  • 4
  • 33
  • 57
  • 2
    Downvoters: Please explain your votes. It helps everyone learn. – showdev Oct 30 '13 at 21:05
  • 1
    @showdev this is an answer that would be best suited as a comment as it is just a list of links... – Naftali Oct 30 '13 at 21:06
  • 2
    It's not just a list of links. He's suggesting the use of a particular library as well as specific functions in that library. Regardless, the question is too broad and so the answer can't be very specific. But I don't like the idea of punishing someone who tries to help answer a poorly written question. – webbiedave Oct 30 '13 at 21:21
  • 1
    Agreed, @Neal if we handed out downvotes for answers on bad questions I would have no rep left! (edit: from the negative score when I would downvote the answer, not because I would be downvoted ;)) – rlemon Oct 30 '13 at 21:57