0

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.

  • 1
    Possible duplicate of [Bitmask in PHP for settings?](https://stackoverflow.com/questions/5319475/bitmask-in-php-for-settings) – Alexei Levenkov Dec 29 '18 at 23:36
  • edited, in last paragraph i pointed out the difference – DevilishSkull Dec 29 '18 at 23:46
  • With your devilish skills you should easily understand that manipulation of each bit is independent of other bits... so there is no difference whether you are setting one single bit or multiple of them. – Alexei Levenkov Dec 30 '18 at 00:04
  • I think you are not right. `$number = ($number & ~(1 << $n)) | ($new_bit << $n)` won't be working for me at least for the reason that there is no valid `$n` when `$type` isn't a power of two. – DevilishSkull Dec 30 '18 at 09:44

1 Answers1

1

You need to perform a different operation in setPermission dependent on whether $value is true or false. Your current code only implements the case where you want to clear permissions ($value = false).

function setPermission(int $permissions, int $type, bool $value)
{
    if ($value)
        return $permissions | $type;
    else
        return $permissions & ~$type;
}

Demo on 3v4l.org

Nick
  • 138,499
  • 22
  • 57
  • 95