不确定我是否完全理解,但如果您以未对齐/未填充的格式打包数据,您将需要使用某种比特流。
这是一个简单的类。理想情况下,它会是某种接受资源流的迭代器,但直接通过字符串显示如何做到这一点更简单:
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];
}
如果该函数被优化为一次读取最多 8 位,则该readBits()
函数会更快,但按原样理解要简单得多。