<?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