Created
May 16, 2012 05:51
-
-
Save jbarciauskas/2707847 to your computer and use it in GitHub Desktop.
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 | |
class BitArray { | |
//Sacrifice 2x the amount of memory, so we can use pack/unpack easily | |
const INT_SIZE = 4; | |
private $bitmapString; | |
public function __construct($numberOfBits = 64, $bitmapString = null) { | |
if($bitmapString!= null) | |
$this->bitmapString = $bitmapString; | |
else { | |
if($numberOfBits == null) | |
throw new InvalidArgumentException("numberOfBits or bitmapString is required"); | |
$numberOfInts = $numberOfBits / self::INT_SIZE / 8; // PHP_INT_SIZE is in bytes | |
for($i = 0; $i < $numberOfInts; $i++) { | |
$this->bitmapString .= pack("L", 0); | |
} | |
} | |
} | |
public function setBit($bit) { | |
$this->bitmapString = $this->bitmapString | $this->getBitStr($bit); | |
} | |
public function unsetBit($bit) { | |
$this->bitmapString = $this->bitmapString & (~($this->getBitStr($bit))); | |
} | |
private function getBitStr($bit) { | |
$index = floor($bit / self::INT_SIZE / 8); | |
$bitInIndex = $bit % (self::INT_SIZE * 8); | |
$bitStr = ""; | |
for($i = 0; $i < $index; $i++) { | |
$bitStr .= pack("L", 0); | |
} | |
$numToSet = pow(2, $bitInIndex); | |
$bitStr .= pack("L", $numToSet); | |
return $bitStr; | |
} | |
public function toIntArray() { | |
$intIndex = 0; | |
$retArray = array(); | |
for($j = 0; $j < $this->length(); $j += self::INT_SIZE) { | |
$charsToUnpack = mb_substr($this->bitmapString, $j, self::INT_SIZE, '8bit'); | |
$intInArray = unpack("L", $charsToUnpack); | |
$intInArray = $intInArray[1]; | |
for($i = 0; $i < (self::INT_SIZE * 8); $i++) { | |
if(($intInArray | pow(2, $i)) == $intInArray) { | |
$retArray[] = $intIndex; | |
} | |
$intIndex++; | |
} | |
} | |
return $retArray; | |
} | |
public function length() { | |
return mb_strlen($this->bitmapString, '8bit'); | |
} | |
public function __tostring() { | |
return $this->bitmapString; | |
} | |
public static function orFn($thisBitArray, $thatBitArray) { | |
return new BitArray(null, $thisBitArray->__tostring() | $thatBitArray->__tostring()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment