<?php
class TBit {
private $error;
private $arrBit;
private $strBit;
private $length;
public function __construct($val, $int=32) {
if($int >= 33) {
$this->error = new Exception("max. 32 Flags allowed");
} else {
$this->length = $int - 1;
$this->setArray($val);
$this->toBit($val);
}
}
public function setArray($dec=0){
for($i = 0; $i <= $this->length; $i++) {
$this->strBit .= Bit::boolInt(false);
}
return $this;
}
/**
* toBit
* @param int $dec
* @return void
*/
public function toBit( $dec ) {
$this->strBit = str_pad((string)decbin($dec),$this->length,"0",STR_PAD_LEFT);
foreach(str_split($this->strBit, 1) as $key => $val){
$this->arrBit[$key] = Bit::intBool($val);
}
return $this;
}
public function set($index, $value) {
if($index >= $this->length) return false;
if(!is_bool($value)){
$this->error = new Exception("expecting a boolean value");
} else {
$this->arrBit[$index] = Bit::boolInt($value);
$this->strBit = str_pad((string)implode("",$this->arrBit),$this->length,"0",STR_PAD_LEFT);
}
return $this;
}
public function add(array $value) {
if(!is_bool($value)) {
$this->error = new Exception("Expecting boolean value");
} else {
for($i=0; $i <= $this->length; $i++) {
$this->arrBit[$i] = Bit::boolInt($value);
}
$this->strBit = str_pad((string)implode("",$this->arrBit),$this->length,"0",STR_PAD_LEFT);
}
return $this;
}
private static function boolInt($value) {
return (int)($value==true?1:0);
}
private static function intBool($value) {
return (bool)($value==1?true:false);
}
/**
* getDecimal
* @return int
*/
public function get(){
return $this->getDecimal();
}
public function getDecimal(){
return bindec($this->strBit);
}
public function getBinary(){
return $this->strBit;
}
public function getArray(){
return $this->arrBit;
}
public function __toString() {
if($this->error instanceof Exception){
return $this->error;
}
return $this->getDecimal();
}
}