Created
January 24, 2012 22:27
-
-
Save arnaud-lb/1673119 to your computer and use it in GitHub Desktop.
Array of booleans stored in a string
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
<?php | |
/** | |
* @author Arnaud Le Blanc <[email protected]> | |
*/ | |
class Bitfield implements ArrayAccess | |
{ | |
protected $field; | |
public function __construct($size) | |
{ | |
$this->field = str_repeat("\xFF", ceil($size / 8)); | |
} | |
public function offsetGet($offset) | |
{ | |
$char = ord($this->field[$offset >> 3]); | |
return (bool) ($char & (1 << ($offset & 7))); | |
} | |
public function offsetSet($offset, $value) | |
{ | |
$char = ord($this->field[$offset >> 3]); | |
if ($value) { | |
$char |= 1 << ($offset & 7); | |
} else { | |
$char &= ~(1 << ($offset & 7)); | |
} | |
$this->field[$offset >> 3] = chr($char); | |
} | |
public function offsetUnset($offset) | |
{ | |
$this->offsetSet($offset, false); | |
} | |
public function offsetExists($offset) | |
{ | |
return $this->offsetGet($offset); | |
} | |
} | |
// bitfield with 255 booleans initialized to true | |
$field = new Bitfield(255); | |
var_dump($field[42]); // true | |
$field[42] = false; | |
var_dump($field[42]); // false | |
$field[42] = true; | |
var_dump($field[42]); // true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment