Re: Bitwise operations criticism needed

From: Date: Tue, 31 Aug 2004 16:31:46 +0000
Subject: Re: Bitwise operations criticism needed
References: 1 2 3 4  Groups: php.general 
Request: Send a blank email to php-general+get-195301@lists.php.net to get a copy of this message
Marek Kilimajer wrote:
Your checks are something like if($user['tom'] & $perm['read']) echo 'Tom can read'; Only the 3rd bit is checked, all others are ignored and won't do any harm. Anyway, the "clean" way of setting permissions is: $user['tom'] = $perm['execute'] | $perm['write'] | $perm['read'];
Understood. It cant be illegal if its set as you described.
$compare = $perm_total & $user_perm; unsets all bits other than 1, 2 and 4, so 0 =< $compare =< 7. However, your first condition already did this.
Ok. So here is the updated code -> -- start code -- <?php $perm = $user = array(); $perm_total = 0; // Permissions from some source like a database/file $perm['execute'] = 1; $perm['write'] = 2;
$perm['read']    = 4;
// User permissions (predetermined) from sessions maybe
$user['tom']            = $perm['read'] | $perm['write'] | $perm['execute'];  // rwx
$user['joe']            = $perm['read'] | $perm['execute'];  // rx
$user['whats_his_face'] = $perm['read'] | $perm['write']; // rw // Set the sum of "source" permissions foreach($perm as $value) {
    $perm_total |= $value;
} echo "<ul>"; // Loop over the users foreach($user as $id => $user_perm) {
    // Compare user bits to permission bits
    $compare = $perm_total & $user_perm;
    // Make it an even 4 bit string (for visual effect)
    $bits_string = sprintf("%03d", decbin( $compare ));
    echo "<li>User: " . $id . "</li>";
    // Check to see if the comparision contains any permission bits
    $can_read    = (($compare & $perm['read']) == $perm['read']) === TRUE ? "TRUE" : "FALSE";
    $can_write   = (($compare & $perm['write']) == $perm['write']) === TRUE ? "TRUE" : "FALSE";
    $can_execute = (($compare & $perm['execute']) == $perm['execute']) === TRUE ? "TRUE" : "FALSE";
    echo "<ul>";
    echo "<li>" . $user_perm . ' -> ' . $bits_string . "</li>";
    echo "<li>Can Read: $can_read</li>";
    echo "<li>Can Write: $can_write</li>";
    echo "<li>Can Execute: $can_execute</li>";
    echo "</ul>";
} echo "</ul>"; ?> -- end code -- So if thats it, now its time to expand on this idea on my end... Thanks

« previous php.general (#195301) next »