2012-07-25 31 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