某一個字段用於存儲商品的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