Skip to content

Instantly share code, notes, and snippets.

@LaffinToo
Created May 3, 2014 04:05
Show Gist options
  • Save LaffinToo/5405bc2f0a4687e922db to your computer and use it in GitHub Desktop.
Save LaffinToo/5405bc2f0a4687e922db to your computer and use it in GitHub Desktop.
Bit Manipulation Class - Using strings as a bitstring allowing for huge amount of toggles #Bits
<?php
/*
* Bitman.php
*
* Copyright 2014 Luis "Laffin" Espinoza <laffintoo@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*
*
*/
/*
* Class Bitman
*/
class Bitman
{
public $bitstring;
private $char_pos,$bit;
/**
* Constructor of class bitfun.
*
* @return void
*/
public function __construct($bitstring=NULL)
{
if($bitstring==NULL) $bitstring=chr(0);
$this->bitstring=$bitstring;
}
public function getBitString()
{
return $this->bitstring;
}
private function SetPos($position)
{
$this->char_pos=(int)($position / 8);
$this->bit=$position % 8;
if(strlen($this->bitstring)<$this->char_pos)
$this->bitstring=$this->bitstring . str_repeat(chr(0),$this->char_pos - strlen($this->bitstring));
}
private function GetByte()
{
return ord(substr($this->bitstring,$this->char_pos,1));
}
function SetByte($char)
{
$this->bitstring[$this->char_pos] = chr($char);
}
public function Test($position)
{
$this->SetPos($position);
return ($this->GetByte() & (1<<$this->bit))?1:0;
}
public function Set($position)
{
$this->SetPos($position);
$this->SetByte($this->GetByte() | (1<<$this->bit));
}
public function Clear($position)
{
$this->SetPos($position);
$this->SetByte($this->GetByte() & ~(1<<$this->bit));
}
public function Toggle($position)
{
$this->SetPos($position);
$this->SetByte($this->GetByte() ^ (1<<$this->bit));
}
}
$bs = new Bitman();
for($i=1;$i<255;$i+=2)
{
$bs->Set($i);
}
echo strlen($bs->GetBitString()) .':' . var_export($bs->GetBitString(),1).PHP_EOL;
for($i=0;$i<255;$i++)
{
echo $bs->Test($i);
}
echo PHP_EOL;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment