Created
August 24, 2016 09:05
-
-
Save avataru/5a0594169410580641513ee21037da13 to your computer and use it in GitHub Desktop.
Bitmask class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment