Here is some PHP code for you, but please note that it is rather inefficient. I used this algorithm because:
- He is explicit and uses words, not mathematical tricks, to do the job, and
- It works in situations where you cannot accept the basic implementation of 2s, but still want to "think" in this way. (try to "save" the bitmasks in PHP and think that they will work in JavaScript )
Read the comments and contribute @Paebbels solution. The difference in performance is almost 7x, so actually use it only if it will not be used very often.
It uses base_convert to convert base number 10 to base 2, splits the string into an array of characters, changes the array and then iterates over it, looking for 1 s.
$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"; } }
Conclusion:
14 is one
15 is 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));
Conclusion:
Array ([0] => Three 1 => Four [2] => Seven)
source share