Advertisement
Guest User

Untitled

a guest
Aug 24th, 2016
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.44 KB | None | 0 0
  1. class Bitmask
  2. {
  3. private $bitmask;
  4.  
  5. public function __construct($bitmask = 0)
  6. {
  7. $this->bitmask = $bitmask;
  8. }
  9.  
  10. public function set($bit, $value)
  11. {
  12. if (!is_bool($value)) {
  13. throw \InvalidArgumentException('The value must be either true or false');
  14. }
  15.  
  16. if ($value) {
  17. $this->setOn($bit);
  18. } else {
  19. $this->setOff($bit);
  20. }
  21. }
  22.  
  23. public function toggle($bit)
  24. {
  25. $position = self::getPosition($bit);
  26.  
  27. $this->bitmask ^= $position;
  28. }
  29.  
  30. public function setOn($bit)
  31. {
  32. $position = self::getPosition($bit);
  33.  
  34. $this->bitmask |= $position;
  35. }
  36.  
  37. public function setOff($bit)
  38. {
  39. $position = self::getPosition($bit);
  40.  
  41. $this->bitmask &= ~ $position;
  42. }
  43.  
  44. public function get($bit)
  45. {
  46. $position = self::getPosition($bit);
  47.  
  48. return $this->isOn($bit);
  49. }
  50.  
  51. public function isOn($bit)
  52. {
  53. $position = self::getPosition($bit);
  54.  
  55. return (bool) ($this->bitmask & $position);
  56. }
  57.  
  58. public function isOff($bit)
  59. {
  60. $position = self::getPosition($bit);
  61.  
  62. return ! (bool) ($this->bitmask & $position);
  63. }
  64.  
  65. private static function getPosition($bit)
  66. {
  67. if (!is_integer($bit) || $bit < 1) {
  68. throw \InvalidArgumentException('The bit position must be a non-zero positive integer');
  69. }
  70.  
  71. return pow(2, $bit);
  72. }
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement