Page 1 of 1

bitwise comparison..

Posted: Wed Aug 09, 2006 7:17 pm
by Jenk
Just a quick second opinion please :)

Using binary/bits for a permissions system, for one method (switchPermission - if it's 'on', change to 'off' and vice versa..) is the below (bar any optimisations) correct? My maths is poor and I haven't used bitwise for very long :)

Code: Select all

public function switchPermission ($perm)
    {
        if (!$this->perms & $perm) {
           $this->perms += $perm;
        } else {
           $this->perms -= $perm;
        }
    }
i.e. if I am comparing to permission value 8, I simply add/subtract 8 and this will be independant from all other bits? Or should I go for:

Code: Select all

$this->perms = ($this->perms ^ $perm);
?

Thanks in advance :)

Posted: Wed Aug 09, 2006 7:37 pm
by feyd
xor is the more accurate of the two.

Posted: Thu Aug 10, 2006 3:57 am
by Oren
Use XOR, it's much easier to read the code and understand what it does.

I was actually going to write a chapter about bitwise in our book. So far I hadn't had a chance to do so, but I'm going to do so sooner or later :P

A short example to remind you how it works...

0101 ^ 1110 = 1011

Here is a simple rule: when you do XOR with 1 - the vallue of the bit changes (1 become 0, 0 become 1), when you do XOR with 0 - the value remains the same as it was before the XOR.

XOR:

0101
1110
--------
1011

You see, only the LSB (least significant bit) remains as it was (1).