PHP Bitmap算法

<?php

class Bitmap
{
    private $max_number;
    private $bitmapArr;
    private $php_int_bit_size;
    private $outputSortArr = [];

    // $max_number 最大的数
    public function __construct(int $max_number = 10)
    {
        $this->max_number = $max_number;
        //设置php bitmap存储数组
        $this->bitmapArr = array_fill(0, $max_number, 0);
        //php中默认 int类型占用空间为8byte,即:64bit。如果数组个数设置为的10个,则存储最大不能超过 10 * 64 = 640;
        //php常量PHP_INT_SIZE:int占用的字节数
        $this->php_int_bit_size = PHP_INT_SIZE * 8;
    }

    // 填充的值
    public function shiftBit(array $sortArray = [])
    {
        foreach ($sortArray as $value) {
            if ($this->php_int_bit_size * $this->max_number < $value) {
                throw new \Exception('排序数组中' . $value . '超出最大值,请设置合适的数组', 400);
            }
            $quotient = $value / $this->php_int_bit_size;
            $quotient = floor($quotient);
            $remainde = $value % $this->php_int_bit_size;
            $this->bitmapArr[$quotient] = $this->bitmapArr[$quotient] | (1 << $remainde);
        }
        return $this->bitmapArr;
    }

    // 排序
    public function outputSortResult()
    {
        foreach ($this->bitmapArr as $key => $item) {
            for ($i = 0; $i < $this->php_int_bit_size; $i++) {
                if ((1 << $i) & $item) {
                    //存在数字
                    $this->outputSortArr[] = $key * $this->php_int_bit_size + $i;
                }
            }
        }
        return $this->outputSortArr;
    }
}


$BitMap = new Bitmap(1);
$BitMap->shiftBit([3,2,6]);
$sortResult = $BitMap->outputSortResult();
var_dump($sortResult);

假设以1个字节为一个单元,总共有8个bit,可放8个数字
以十进制6为例:
00000000为初始化,填充进去第7个位置应当为01000000
规则如下:

  • 程序实现:1<<(m%n)
    m:要填充的十进制的数(6)
    n:一个周期的总位数,例当1个字节时,n为8
  • 解释
    以1的二进制(00000001)为第一个非0的初始化位置,1向左移动2个位(1<<6),变成01000000,十进制为64
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值