Here's some PHP code for you, but please note it is pretty inefficient. I have used this algorithm because:
- It is explicit and uses words rather than mathematical tricks to get the job done, and
- Works in situations where you can't assume an underlying implementation of 2s complement, but still want to 'think' that way. (try 'storing' bitmasks in PHP and thinking they will work in JavaScript)
Please read the comments and implement @Paebbels solution. The difference in performance is almost 7x, so really only use this if it will not be used very often.
It utilizes base_convert
to convert the base 10 integer to base 2, splits the string into a character array, reverses the array and then iterates over it looking for 1s.
$mask = 49152; // 0xC000
// Find which positions in the mask contain a '1'
$bitArray = array_reverse(str_split(base_convert($mask, 10, 2)));
foreach($bitArray as $k => $v) {
if($v) {
echo $k . " is a one\n";
}
}
Output:
14 is a one
15 is a one
As a function:
function extractElements($mask, array $input)
{
$output = array();
$bitArray = array_reverse(str_split(base_convert($mask, 10, 2)));
foreach($bitArray as $k => $v) {
if($v && isset($input[$k])) {
$output[] = $input[$k];
}
}
return $output;
}
$mask = 76; // 0x4C
$input = [
'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight'
];
print_r(extractElements($mask, $input));
Output:
Array
(
[0] => Three
1 => Four
[2] => Seven
)