用位图BitMap节省空间

某一个字段用于存储商品的id和商品分类id,假设分类id小于等于255,商品id小于等65535,如果用int存储,在32位机器上至少要64位,而采用位图则只需要32位即可。

class Bits
{
    protected $bits = 0;

    function setGoodId($goodId)
    {
        $this->bits += $goodId << 8;
    }
    
    function setCateId($cateId)
    {
        $this->bits += $cateId;
    }
    
    function getCateId()
    {
        return $this->bits & 255;
    }
    
    function getGoodId()
    {
        return $this->bits  >> 8;
    }

    function show()
    {
        return $this->bits;
    }
}

$cateId = 234; //分类id小于等于255(2的8次方)
$goodId = 12345; //商品id小于等于65535(2的16次方)
$obj = new Bits();
$obj->setCateId($cateId);
$obj->setGoodId($goodId);
echo $obj->getGoodId() . "\n";
echo $obj->getCateId() . "\n";
echo $obj->show();
[Running] php "/Users/why/Desktop/php/why.php"
12345
234
3160554
发布了253 篇原创文章 · 获赞 46 · 访问量 18万+

猜你喜欢

转载自blog.csdn.net/why444216978/article/details/105019096
今日推荐