Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Bitmask
- {
- private $bitmask;
- public function __construct($bitmask = 0)
- {
- $this->bitmask = $bitmask;
- }
- public function set($bit, $value)
- {
- if (!is_bool($value)) {
- throw \InvalidArgumentException('The value must be either true or false');
- }
- if ($value) {
- $this->setOn($bit);
- } else {
- $this->setOff($bit);
- }
- }
- public function toggle($bit)
- {
- $position = self::getPosition($bit);
- $this->bitmask ^= $position;
- }
- public function setOn($bit)
- {
- $position = self::getPosition($bit);
- $this->bitmask |= $position;
- }
- public function setOff($bit)
- {
- $position = self::getPosition($bit);
- $this->bitmask &= ~ $position;
- }
- public function get($bit)
- {
- $position = self::getPosition($bit);
- return $this->isOn($bit);
- }
- public function isOn($bit)
- {
- $position = self::getPosition($bit);
- return (bool) ($this->bitmask & $position);
- }
- public function isOff($bit)
- {
- $position = self::getPosition($bit);
- return ! (bool) ($this->bitmask & $position);
- }
- private static function getPosition($bit)
- {
- if (!is_integer($bit) || $bit < 1) {
- throw \InvalidArgumentException('The bit position must be a non-zero positive integer');
- }
- return pow(2, $bit);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement