For example I have an integer
$mask = 210;
which in binary is
$binary = decbin($mask); // "11010010"
Now I want to convert this ($mask or $binary) to an array with the indexes which is true:
$expected = [2, 5, 7, 8];
What is the best way to do this?
For example I have an integer
$mask = 210;
which in binary is
$binary = decbin($mask); // "11010010"
Now I want to convert this ($mask or $binary) to an array with the indexes which is true:
$expected = [2, 5, 7, 8];
What is the best way to do this?
You can do this manually:
$expected = array();
$mask = 210;
$binary = strrev(decbin($mask)); // strrev reverts the string
for ($i = 0; $i < strlen($binary); $i++)
{
if ($binary[$i] === '1') $expected[] = ($i + 1);
}
Working IDEOne demo.
Important note: bits are usually being numerated from zero. So, the correct answer would be "1 4 6 7". Change ($i + 1) to $i in order to achieve this result.
Split $binary to an array, push a 0 to give yourself offsets from 1 rather than from zero, reverse it, filter to remove falsey values, and get the keys
$mask = 210;
$binary = decbin($mask); // "11010010"
$tmp = str_split($binary, 1);
$tmp[] = 0;
$expected = array_keys(
array_filter(
array_reverse($tmp)
)
);
var_dump($expected);