1

I have int field representing bitmask. Is there any functions available to work with bitmask? issetBit, unsetBit, setBit?

Thank you

Kirzilla
  • 16,368
  • 26
  • 84
  • 129

2 Answers2

7

Use bitwise operators. But if you want functions, here you have some.

function issetBit(& $mask, $bit) {
    return (bool)($mask & (1 << $bit));
}

function unsetBit(& $mask, $bit) {
    $mask &= ~(1 << $bit);
}

function setBit(& $mask, $bit) {
    $mask |= (1 << $bit);
}

Usage: first argument is your current bitmask; second argument is the number of the bit (zero-based). I.e. issetBit($mask, 2) equals (bool)($mask & 4) You cannot test/set/unset more than one bit at once with those functions though.

mario
  • 144,265
  • 20
  • 237
  • 291
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
  • thanks, I am trying to learn as much about using these in PHP, I think the main motivation is that it is a challenge for me and not beginner type code IMO. Here is my questions/answers for my post so far if you care to look/contribute ... http://stackoverflow.com/questions/5319475/bitmask-in-php-for-settings – JasonDavis Mar 16 '11 at 19:19
  • If you get a chance, could you possibly show an example using your functions above, please? – JasonDavis Mar 16 '11 at 20:20
2

You want the Bitwise Operators: http://php.net/manual/en/language.operators.bitwise.php

Stephen
  • 18,597
  • 4
  • 32
  • 33