Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get array values based on bitmask in PHP

I have a 32-bit integer used for bitmask and an array with 32 values. How to get only those values from the array which indexes correspond to the positions of the non-zero bits in the bitmask?

For example let say that the bitmask is 49152 which is 1100000000000000 in binary. Therefore I have to take the values of elements with indexes 14 and 15 from the array.

like image 821
Nikola Obreshkov Avatar asked Dec 17 '14 22:12

Nikola Obreshkov


People also ask

What is array_values() function in PHP?

PHP array_values () is a built-in function that returns all the values of an array and not the keys. The array_values () function returns the array containing all the values of an array. The returned array will have the numeric keys, starting at 0 and increasing by 1.

How to search for a specific value in an array?

If you array values are regular expressions, you can use this function: function array_pcresearch ($haystack, $needle) { foreach ($haystack as $key => $val) { if (preg_match ($val, $needle)) { return $key; } } return false; }

What is the difference between $array_values() and $bigarray?

array_values () returns all the values from the array and indexes the array numerically. The array. Returns an indexed array of values. Just a warning that re-indexing an array by array_values () may cause you to reach the memory limit unexpectly. and says there's a BIG array $bigArray which allocate 5MB of memory.

What happens when you re-index an array by array_values()?

Just a warning that re-indexing an array by array_values () may cause you to reach the memory limit unexpectly. and says there's a BIG array $bigArray which allocate 5MB of memory. it just re-index it into another array, and assign to itself later. Most of the array_flatten functions don't allow preservation of keys.


1 Answers

You will need to loop in 32 steps over your mask and test it for '1', if this bit is set, you can copy the element to your resulting array.

Pseudo code:

m = 0x00000001
j = 0
for i in 0 to 31 loop
  if ((mask & m) = m) then   // bit is set in mask
    result(j++) := input(i)
  end if
  m := m << 1     // shift left by 1 or multiply by 2
end loop
like image 188
Paebbels Avatar answered Sep 21 '22 15:09

Paebbels