ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

在PHP中按位解包

2019-10-13 04:31:50  阅读:249  来源: 互联网

标签:unpack php bit byte


我想通过8-8-8-7位的奇怪序列将二进制字符串解压缩为数组.

对于正常的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位,所以我想不出任何合适的方法.

你有什么主意吗?

解决方法:

不知道我是否完全理解,但是如果您以未对齐/未填充的格式打包数据,则将需要使用某种比特流.

这是一个简单的类.理想情况下,它将是某种接受资源流的迭代器,但是显示如何直接通过字符串进行操作则更为简单:

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位,它将更快,但是按原样理解它要简单得多.

标签:unpack,php,bit,byte
来源: https://codeday.me/bug/20191013/1905334.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有