如何检查PHP中的位是1还是0?
我需要遍历一个大文件并检查每个位,无论是1还是0,并根据设置的“列长度”将其放入多维数组中。
类似的东西:
$binary = 0100110110110001100010001111101100111;
$binary=binaryToArray($binary,10);
结果如下:
array[0][0]=0; array[0][1]=1; array[0][2]=0; //etc.
array[1][0]=1; array[1][1]=1; array[1][2]=0; //etc.
答案 0 :(得分:2)
您可以编写一个包装数据的类,并返回另一个包装该字节的类的实例:
class DataBitAccessor implements ArrayAccess {
private $data;
public __construct($data) {
$this->data = $data;
}
public offsetExists($offset) {
return is_int($offset) &&
$offset >= 0 && $offset < strlen($this->data);
}
public offsetGet($offset) {
if (!$this->offsetExists($offset)) {
return null;
}
return new Byte($this->data{$offset});
}
public offsetSet($offset, $value) {
throw new LogicException();
}
public offsetUnset($offset) {
throw new LogicException();
}
}
class Byte implements ArrayAccess {
private $byte;
public __construct($byte) { $this->byte = ord($byte); }
public offsetExists($offset) {
return is_int($offset) &&
$offset >= 0 && $offset < 8;
}
public offsetGet($offset) {
if (!$this->offsetExists($offset)) {
return null;
}
return ($this->byte >> $offset) & 0x1;
}
public offsetSet($offset, $value) {
throw new LogicException();
}
public offsetUnset($offset) {
throw new LogicException();
}
}
(未测试的)
您也可以直接从DataBitAccessor
return str_pad(base_convert(
ord($this->data[$offset]), 10, 2), 8, "0", STR_PAD_LEFT);