开发者

Effeciently finding a permission "bit" in number

I'm working with a system that uses the following permission scheme:

1 - Permission A

2 - Permission B

4 - Permission C

8 - Permission D

16 - Permission E

The permissions for a user is stored as the sum of the permission values. For example, if a user has permissions B, C, and D, 14 is the number that is stored. (2+4+8)

Is there开发者_StackOverflow社区 a fast way to find out if the user has permission D that doesn't involve a full expansion of the permission string? (Taking a power of two until greater than the stored number, subtracting off that power, until the target number is reached)


http://php.net/manual/en/language.operators.bitwise.php

$has_D = $perms & 8;

or

$has_Nth_perm = $perms & (1 << ($n-1));

or

function has_nth_perm($perms, $n) {
    return $perms & (1 << ($n-1));
}


The fastest way is doing bitwise operation:

$D_PERMISSION = 0x08
if( $permission & $D_PERMISSION ) { do_stuff(); }


Have a look at bitwise operators.


//////////////////////////////////////////////////////////////////////////
// LONGINT_DEC2BIN
// 64-bit manipulation safe even on 32-bit systems
// $dec_str is a DECIMAL integer or a string of decimal digits
// returns binary looking string with 0's and 1's
//////////////////////////////////////////////////////////////////////////
function longint_Dec2Bin($dec_str) {
    if(longint_is_32()) {
        $dec_str .= ''; // convert to string if not already
        $bin_str='';
        while($dec_str!='0') {
            $bin_str .= chr(48 + ($dec_str{strlen($dec_str)-1}%2));
            if(function_exists('BCDiv')) {
                $dec_str = BCDiv($dec_str,'2');
            } elseif(function_exists('gmp_div_q')) {
                $dec_str = gmp_strval(gmp_div_q($dec_str,'2'));
            } else {
                die("This PHP installation lacks both BCMath and GMP. 32-bit environments like this require one or the other.");
            }
        }
        $bin_str=strrev($bin_str);
        return(($bin_str!='')?$bin_str:'0');
    } else {
        return decbin($dec_str);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜