Created
January 24, 2012 22:17
-
-
Save arnaud-lb/1673067 to your computer and use it in GitHub Desktop.
bit field in a string
This file contains 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 <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