Skip to content

Instantly share code, notes, and snippets.

@arnaud-lb
Created January 24, 2012 22:27
Show Gist options
  • Save arnaud-lb/1673119 to your computer and use it in GitHub Desktop.
Save arnaud-lb/1673119 to your computer and use it in GitHub Desktop.
Array of booleans stored in a string
<?php
/**
* @author Arnaud Le Blanc <arnaud.lb@gmail.com>
*/
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