Skip to content

Instantly share code, notes, and snippets.

@arnaud-lb
Created January 24, 2012 22:17
Show Gist options
  • Save arnaud-lb/1673067 to your computer and use it in GitHub Desktop.
Save arnaud-lb/1673067 to your computer and use it in GitHub Desktop.
bit field in a string
<?php
/**
* @author Arnaud Le Blanc <arnaud.lb@gmail.com>
*/
// 255*8 booleans initialized to true
$field = str_repeat("\xFF", 255);
function read_bit(&$str, $offset)
{
list(, $char) = unpack('c', $str[$offset >> 3]);
return (bool) ($char & (1 << ($offset & 7)));
}
function set_bit(&$str, $offset)
{
list(, $char) = unpack('c', $str[$offset >> 3]);
$char |= 1 << ($offset & 7);
$str[$offset >> 8] = pack('c', $char);
}
function unset_bit(&$str, $offset)
{
list(, $char) = unpack('c', $str[$offset >> 3]);
$char &= ~(1 << ($offset & 7));
$str[$offset >> 3] = pack('c', $char);
}
var_dump(read_bit($field, 42)); // true
unset_bit($field, 42);
var_dump(read_bit($field, 42)); // false
set_bit($field, 42);
var_dump(read_bit($field, 42)); // true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment