2

I have an array of 1000+ items. the value in each index is either 1 or 0. I want to be able to do bitwise operations such as counting the number of 1's and also finding the 1's location on this array which would entail converting the array into a binary number and then into a decimal number and performing bitwise operations (which would be very fast and efficient)

So imagine something like this:

$array = array(
    "foo" => 1,
    "bar" => 0,
    "test"=> 0,
...
);

I can use implode to convert the array values into a string.

$str = implode('', $array);

This gives me 100. but in order for me to do any bitwise operation I first need to turn this in to a decimal number and if the size of the array (number of bits) is more than 64 (64 bit machine), things don't work:

$b = bindec($str);  // will fail
$c = $b | 7;

Similarly if I have to do any shifting or counting of 1's etc. things don't work.

Anyone has any idea on how to overcome this problem in php.

6
  • if you don't accept correct answer, don't expect anyone to help you Commented Aug 6, 2014 at 15:08
  • What's wrong with array_sum($array) for counting the 1s? And using array_unshift($array, array_pop($array)) and array_push($array,array_shift($array)) for shifting? Commented Aug 6, 2014 at 15:08
  • You don't have to convert a number to any base if you want to do bitwise operations. You can even do bitwise operation on a string. Also keep in mind the byteorder, it is easier to work with the smallest nibble on the right. Commented Aug 6, 2014 at 15:09
  • sum is not bitwise operation. Commented Aug 6, 2014 at 15:11
  • 1
    @EGN I also don't think the answer of sectus is correct, since it too doesn't work for array lengths over 64. This was explicitly asked by the OP. Commented Sep 15, 2017 at 11:43

1 Answer 1

1

Just make some bitwise manipulation

$array = array( "foo" => 1, "bar" => 0, "test"=> 1, );

$mask = 0;
$i = 0;
foreach($array as $value)
{
$mask |= $value << $i;
$i++;
}

var_dump($mask); // 5
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.