Skip to content

Instantly share code, notes, and snippets.

@avataru
Created August 24, 2016 09:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save avataru/5a0594169410580641513ee21037da13 to your computer and use it in GitHub Desktop.
Save avataru/5a0594169410580641513ee21037da13 to your computer and use it in GitHub Desktop.
Bitmask class
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