2012-07-25 46 views
1

我想通過8-8-8-7位的奇怪序列將二進制字符串解壓縮到數組中。在PHP中按位排序

我可以很容易地做這樣的事情,對於一個正常的8-8-8-8順序:

$b=unpack('C*',$data); 
for ($i=0,$count=sizeof($b); $i < $count; $i+=4) { 
$out[]=array($b[$i+1],$b[$i+2],$b[$i+3],$b[$i+4]); 
} 

這會給我的字節二維數組,由4

分組但作爲第四個7位,我只是想不出任何適當的東西。

你有什麼想法嗎?

+0

使用&操作符可能會有所幫助 – 2012-07-25 16:10:05

+0

我在想如何...... – Anonymous 2012-07-25 16:10:48

+0

所以你想要讀取一個緊密排列在一起的31位數據格式?什麼是用例? – Matthew 2012-07-25 17:08:16

回答

3

不知道我是否完全理解,但如果您已經以非對齊/無襯墊格式打包數據,您將需要使用某種比特流。

這是一個簡單的類。理想情況下這將是某種形式的迭代器,它接受一個資源流,但顯示瞭如何通過一個字符串做直接比較簡單:

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位數據,則​​速度會更快,但按原樣理解要簡單得多。

+0

謝謝,這是一個很好的例子,它的工作原理 – Anonymous 2012-07-26 15:01:29