不知道我是否完全理解,但如果您已經以非對齊/無襯墊格式打包數據,您將需要使用某種比特流。
這是一個簡單的類。理想情況下這將是某種形式的迭代器,它接受一個資源流,但顯示瞭如何通過一個字符串做直接比較簡單:
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