I am trying to do some work with permissions stored in integer using bitwise operators, and went stuck trying to set several definite bits to 1
or 0
in one line.
My current code is:
function setPermission(int $permissions, int $type, bool $value)
{
return ($permissions & ~$type) | /* There is what i don't know how to do */;
}
echo setPermission(2|4|16, 4|8, false); // 2|16
echo setPermission(2|4|16, 4|8, true ); // 2|4|8|16
echo setPermission(1|2|4, 4|8|16, false); // 1|2
By analyzing the problem i find out how to do the first part of the function and that the second one must be equal to $type when $value
is true
, and to 0
when $value
is false
, but i don't know how to do that in the easiest way.
I draw your attention that parameter $type
may be any integer, not only the power of two.