比特和位掩码是我一直在努力理解的东西,但我想学习如何将它们用于PHP中的设置和类似的东西.
我终于找到了一个声称要做到这一点的课程,而且正如我所知,它似乎有效,但我不确定这是否是最好的方法.我将使用下面的示例代码发布类文件,以便按工作顺序显示它.
如果您有经验,请告诉我是否可以改进,性能或其他任何方面.我真的很想学习这个,而且我一直在阅读它,但到目前为止我很难掌握它.
班级...
<?php
class bitmask
{
/**
* This array is used to represent the users permission in usable format.
*
* You can change remove or add valuesto suit your needs.
* Just ensure that each element defaults to false. Once you have started storing
* users permsisions a change to the order of this array will cause the
* permissions to be incorectly interpreted.
*
* @type Associtive array
*/
public $permissions = array(
"read" => false,
"write" => false,
"delete" => false,
"change_permissions" => false,
"admin" => false
);
/**
* This function will use an integer bitmask (as created by toBitmask())
* to populate the class vaiable
* $this->permissions with the users permissions as boolean values.
* @param int $bitmask an integer representation of the users permisions.
* This integer is created by toBitmask();
*
* @return an associatve array with the users permissions.
*/
public function getPermissions($bitMask = 0)
{
$i = 0;
foreach ($this->permissions as $key => $value)
{
$this->permissions[$key] = (($bitMask & pow(2, $i)) != 0) ? true : false;
// Uncomment the next line if you would like to see what is happening.
//echo $key . " i= ".strval($i)." power=" . strval(pow(2,$i)). "bitwise & = " . strval($bitMask & pow(2,$i))."<br>";
$i++;
}
return $this->permissions;
}
/**
* This function will create and return and integer bitmask based on the permission values set in
* the class variable $permissions. To use you would want to set the fields in $permissions to true for the permissions you want to grant.
* Then call toBitmask() and store the integer value. Later you can pass that integer into getPermissions() to convert it back to an assoicative
* array.
*
* @return int an integer bitmask represeting the users permission set.
*/
function toBitmask()
{
$bitmask = 0;
$i = 0;
foreach ($this->permissions as $key => $value)
{
if ($value)
{
$bitmask += pow(2, $i);
}
$i++;
}
return $bitmask;
}
}
?>
Run Code Online (Sandbox Code Playgroud)
如何将权限设置/保存为位掩码值?
<?php
/**
* Example usage
* initiate new bitmask object
*/
$perms = new bitmask();
/**
* How to set permissions for a user
*/
$perms->permissions["read"] = true;
$perms->permissions["write"] = true;
$perms->permissions["delete"] = true;
$perms->permissions["change_permissions"] = true;
$perms->permissions["admin"] = false;
// Converts to bitmask value to store in database or wherever
$bitmask = $perms->toBitmask(); //in this example it is 15
$sql = "insert into user_permissions (userid,permission) values(1,$bitmask)";
echo $sql; //you would then execute code to insert your sql.
?>
Run Code Online (Sandbox Code Playgroud)
获取位掩码值并根据位值为每个数组项返回true/false的示例....
<?php
/**
* Example usage to get the bitmask value from database or session/cache.... then put it to use.
* $permarr returns an array with true/false for each array value based on the bit value
*/
$permarr = $perms->getPermissions($bitmask);
if ($permarr["read"])
{
echo 'user can read: <font color="green">TRUE</font>';
}
else {
echo 'user can read: <font color="red">FALSE</font>';
}
//user can WRITE permission
if ($permarr["write"])
{
echo '<br>user can write: <font color="green">TRUE</font>';
}
else {
echo '<br>user can write: <font color="red">FALSE</font>';
}
?>
Run Code Online (Sandbox Code Playgroud)
sve*_*ens 32
通常,位字段是处理标志或任何布尔值集的非常方便和有效的工具.
要了解它们,首先需要知道二进制数是如何工作的.之后,您应该查看按位运算符的手动条目,并确保您知道按位AND,OR和左/右移位的工作原理.
位字段只不过是一个整数值.假设我们的位域大小是固定的,只有一个字节.计算机使用二进制数,所以如果我们的数字的值是29
,你实际上会0001 1101
在内存中找到.
使用按位AND(&
)和按位OR(|
),您可以单独读出并设置数字的每个位.它们都将两个整数作为输入,并分别对每个位执行AND/OR.
要读出你的号码的第一位,你可以这样做:
0001 1101 (=29, our number)
& 0000 0001 (=1, bit mask)
= 0000 0001 (=1, result)
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,您需要一个特殊的数字,其中只有我们感兴趣的位被设置,这就是所谓的"位掩码".在我们的例子中1
.为了读出第二位,我们必须将位掩码中的一个"推"到左边一位.我们可以使用左移位运算符($number << 1
)或乘以2来实现.
0001 1101
& 0000 0010
= 0000 0000 (=0, result)
Run Code Online (Sandbox Code Playgroud)
您可以为我们的号码中的每一位做到这一点.我们的数字和位掩码的二进制AND导致为零,这意味着该位不是"置位",或者是非零整数,这意味着该位已设置.
如果要设置其中一个位,可以使用按位OR:
0001 1101
| 0010 0000 (=32, bit mask)
= 0011 1101 (=29+32)
Run Code Online (Sandbox Code Playgroud)
但是,当你想要"清除"一点时,你将不得不采取不同的方式.
更通用的方法是:
// To get bit n
$bit_n = ($number & (1 << $n)) != 0
// Alternative
$bit_n = ($number & (1 << $n)) >> $n
// Set bit n of number to new_bit
$number = ($number & ~(1 << $n)) | ($new_bit << $n)
Run Code Online (Sandbox Code Playgroud)
起初它可能看起来有点神秘,但实际上它很容易.
到目前为止,你可能发现位字段是一种相当低级的技术.这就是为什么我建议不要在PHP或数据库中使用它们.如果你想要一堆标志它可能没问题,但对于其他任何你真的不需要它们.
你发布的课程对我来说有点特别.例如,像是... ? true : false
非常糟糕的做法.如果你想使用位字段,你最好定义一些常量并使用上面描述的方法.想出一个简单的课程并不难.
define('PERM_READ', 0);
define('PERM_WRITE', 1);
class BitField {
private $value;
public function __construct($value=0) {
$this->value = $value;
}
public function getValue() {
return $this->value;
}
public function get($n) {
return ($this->value & (1 << $n)) != 0;
}
public function set($n, $new=true) {
$this->value = ($this->value & ~(1 << $n)) | ($new << $n);
}
public function clear($n) {
$this->set($n, false);
}
}
$bf = new BitField($user->permissions);
if ($bf->get(PERM_READ)) {
// can read
}
$bf->set(PERM_WRITE, true);
$user->permissions = $bf->getValue();
$user->save();
Run Code Online (Sandbox Code Playgroud)
我没有尝试这个答案的任何代码,但它应该让你开始,即使它没有开箱即用.
请注意,每位字段限制为32个值.
以下是定义位掩码的方法.
// the first mask. In binary, it's 00000001
define('BITWISE_MASK_1', 1 << 0); // 1 << 0 is the same as 1
// the second mask. In binary, it's 00000010
define('BITWISE_MASK_2', 1 << 1);
// the third mask. In binary, it's 00000100
define('BITWISE_MASK_3', 1 << 2);
Run Code Online (Sandbox Code Playgroud)
要检查是否存在位掩码(在本例中为函数参数),请使用按位AND运算符.
function computeMasks($masks) {
$masksPresent = array();
if ($masks & BITWISE_MASK_1)
$masksPresent[] = 'BITWISE_MASK_1';
if ($masks & BITWISE_MASK_2)
$masksPresent[] = 'BITWISE_MASK_2';
if ($masks & BITWISE_MASK_3)
$masksPresent[] = 'BITWISE_MASK_3';
return implode(' and ', $masksPresent);
}
Run Code Online (Sandbox Code Playgroud)
这工作,因为当您或两个字节(比如,00000001
和00010000
),你会得到两个在一起:00010001
.如果你和结果和原始掩码(00010001
比方说00000001
),你得到一个掩码,如果它存在(在这种情况下00000001
).否则,你得到零.