Set permissions in binary

前端 未结 5 2006
说谎
说谎 2020-12-29 16:06

I saw in school a system that set permissions using binary string.

Let\'s say 101001 = 41

So :

  • 1 can be permission to page 1
  • 2 can b
5条回答
  •  感动是毒
    2020-12-29 16:48

    That is the nature of binary - there is only one combination of ones and zeros for each number .

    A function from the PHP comments for decbin:

    function bindecValues($decimal, $reverse=false, $inverse=false) {
    /*
    1. This function takes a decimal, converts it to binary and returns the
         decimal values of each individual binary value (a 1) in the binary string.
         You can use larger decimal values if you pass them to the function as a string!
    2. The second optional parameter reverses the output.
    3. The third optional parameter inverses the binary string, eg 101 becomes 010.
    -- darkshad3 at yahoo dot com
    */
    
        $bin = decbin($decimal);
        if ($inverse) {
            $bin = str_replace("0", "x", $bin);
            $bin = str_replace("1", "0", $bin);
            $bin = str_replace("x", "1", $bin);
        }
        $total = strlen($bin);
    
        $stock = array();
    
        for ($i = 0; $i < $total; $i++) {
            if ($bin{$i} != 0) {
                $bin_2 = str_pad($bin{$i}, $total - $i, 0);
                array_push($stock, bindec($bin_2));
            }
        }
    
        $reverse ? rsort($stock):sort($stock);
        return implode(", ", $stock);
    }
    

    Usage

    $binary_array = bindecValues(41);
    

    This would make binary_array:

    array(1, 8, 32);
    

提交回复
热议问题