...

# matching value using a bitwise operator

crmpicco
09-22-2009, 06:18 PM
I'm new to bitwise operators and the PHP documentation isn't helping my for the code I have below. In the example below \$ulogindetails["securityvalue"] is 34.

... do sumthin' ...
}

Can anyone shed light on how this is working? When would the value match to 880?

Cheers,
Picco

Fou-Lu
09-22-2009, 06:29 PM
AND will return the common bits between the two. 880 & 34 share the 32'nd bit, so it will result in a valid 32.

I get the impression that 880 is supposed to be a singular item, which is not possible, 880 = 512 + 256 + 64 + 32 + 16
While the 34 is 32 + 2, sharing the common 32.

To check if it matches 880 using bitwise (which doesn't make any sense since the bit check is using 880 so a simple comparison will work) you can use if (880 == (\$myVar & 880))
The idea behind bitwise permissions is to take a less aggressive approach to it:

define('CAN_EDIT', 2);
define('CAN_DELETE', 4);
// Do stuff for our 'user', we'll give them privs of 5
{
}
if (\$userPerms & CAN_EDIT)
{
// Our user can edit (this user cannot, since 5 & 2 is 0)
}
if (\$userPerms & CAN_DELETE)
{
// Our user can delete
}

Does that make sense?

bacterozoid
09-22-2009, 06:47 PM
When you think bitwise, think binary.

34 = 0000000000100010
880 = 1000101101110000

In a bitwise AND, if and only if both values are 1, the result will be 1. Anything else is zero. So:

0 & 0 = 0
0 & 1 = 0
1 & 0 = 0
1 & 1 = 1

In a bitwise OR, if any of the values are one, the result will be one. So:

0 | 0 = 0
0 | 1 = 1
1 | 0 = 1
1 | 1 = 1

34 = 0000000000100010 AND
880 = 1000101101110000
--------------------------
0000000000100000

Extended a bit:

34 = 0000000000100010 OR
880 = 1000101101110000
--------------------------
1000101101110010

crmpicco
09-23-2009, 10:59 AM
Thanks for those explanations, I have been reading through them, but i'm still slightly confused as to when the if statement would evaluate and would be true? How would we get into '... do sumthin ...' ?

... do sumthin ...
}

Cheers,
Picco

Fou-Lu
09-24-2009, 06:37 AM
Thanks for those explanations, I have been reading through them, but i'm still slightly confused as to when the if statement would evaluate and would be true? How would we get into '... do sumthin ...' ?

... do sumthin ...
}

Cheers,
Picco

You can't really in this situation. 880 does not represent a valid (singular) bit value, so it can only be comparable by the use of equality (==) or for the use of contained bits.
880 contains the following bit values: 512 + 256 + 64 + 32 + 16. That means as long as the 'securityvalue' contains a number that includes one or more of the above bits (18 for example would match 16 + 2) it will be deemed true.

Lol, my statement doesn't really make sense to you're question. The answer is, it will be false when a comparable number does not include one or more of the following bits: 512, 256, 64, 32, 16. It is true when containing one or more of the previous bits.