不知道我是否完全理解,但如果您已经以非对齐/无衬垫格式打包数据,您将需要使用某种比特流。
这是一个简单的类。理想情况下这将是某种形式的迭代器,它接受一个资源流,但显示了如何通过一个字符串做直接比较简单:
class BitStream
{
private $data, $byte, $byteCount, $bytePos, $bitPos;
private $mask = [0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80];
public function __construct($data)
{
$this->data = $data;
$this->byteCount = strlen($data);
$this->bytePos = 0;
$this->bitPos = 7;
$this->byte = $this->byteCount ? ord($data[0]) : null;
}
// reads and returns 1 bit. null on no more bits
public function readBit()
{
if ($this->byte === null) return null;
// get current bit
$bit = ($this->byte & $this->mask[$this->bitPos]) >> $this->bitPos;
if (--$this->bitPos == -1)
{
// advance to next byte
$this->bitPos = 7;
$this->bytePos++;
$this->byte = $this->bytePos < $this->byteCount ? ord($this->data[$this->bytePos]) : null;
}
return $bit;
}
// reads up to $n bits, where 0 < $n < bit length of max int
// returns null if not enough bits left
public function readBits($n)
{
$val = 0;
while ($n--)
{
$bit = $this->readBit();
if ($bit === null) return null;
$val = ($val << 1) | $bit;
}
return $val;
}
}
然后使用它:
$bs = new BitStream($data);
$out = [];
while (true)
{
$a = $bs->readBits(8);
$b = $bs->readBits(8);
$c = $bs->readBits(8);
$d = $bs->readBits(7);
if ($d === null) break; // ran out of data
$out[] = [$a, $b, $c, $d];
}
的readBits()
功能会如果一次最多可以读取8位数据,则速度会更快,但按原样理解要简单得多。
使用&操作符可能会有所帮助 – 2012-07-25 16:10:05
我在想如何...... – Anonymous 2012-07-25 16:10:48
所以你想要读取一个紧密排列在一起的31位数据格式?什么是用例? – Matthew 2012-07-25 17:08:16