bitwise comparison..

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Jenk
DevNet Master
Posts: 3587
Joined: Mon Sep 19, 2005 6:24 am
Location: London

bitwise comparison..

Post 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 :)
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

xor is the more accurate of the two.
User avatar
Oren
DevNet Resident
Posts: 1640
Joined: Fri Apr 07, 2006 5:13 am
Location: Israel

Post 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).
Post Reply