[php]finding nth bit in binary string. (solved)

Caporegime
Joined
18 Oct 2002
Posts
29,493
Location
Back in East London
Hihi..

Am creating a permissions sytem which uses bitwise/binary to store permissions..

The 'problem' I am facing atm, is that the client can create their own permissions.. thus when I display the permissions, I need to be able to look at the length of the binary string, and loop through each one to see whether it is 'set' or not..
Code:
$perms = '111011';

for ($i = 1; [$i is in $perms]; $i = <this is the bit I can't work out..>) {
    echo (($perms & $i) > 0) ? 'set' : 'not set') . "\n";
}

outputting:
Code:
set
set
not set
set
set
how can I loop through a binary string, whilst knowing what integer value $i will be?

can't substr or explode as that will shift the numbers (explode equating to every number being (int) 1 or (int) 0)

My maths is sucky sucky, so don't know of any equation or anything to do this.

TIA :)

EDIT:

And like the typical 'mate, can you help me out with this? I can't get it to.. oh, nvm.. fixed' situation.. I solved the 'problem' before clicking submit.. and realised it was a hell of a lot simpler than I thought.. so am posting for you all to call me a noob :p

Code:
                while ($row = $db->getRow()) {
                    $perms = decbin($row['permissions']);
                    for ($i = 1, $j = 0; $j < strlen($perms); $i = $i * 2, $j++) {
                        echo (($perms & $i) > 0 ? 'set' : 'not set') . "<br />\n";
                    } 
                }
 
The implementation will still be the same, using strlen(decbin($perms)) to find the number of permissions (each char equates to one permission) :)
 
$perms = binary string. In the below example: '10101' (21)

They are stored as an integer on the DB. I need to use strlen to ascertain how many times to loop through the permissions bits. Whilst at the same time, using the permission bit's integer for other logic.. "set"/"not set" is not the final output.. that's merely a test.

Both give same results:

Code:
                    $perms = decbin($int = 21);
                    for ($i = 1, $j = 0; $j < strlen($perms); $i = $i * 2, $j++) {
                        echo (($int & $i) > 0 ? 'set' : 'not set') . "<br />\n";
                    }
                    echo "<br />\n";
                    $perms = decbin($int = 21);
                    for ($i = 1, $j = 0; $j < strlen($perms); $i = $i * 2, $j++) {
                        echo (($perms & $i) > 0 ? 'set' : 'not set') . "<br />\n";
                    }

outputs:
Code:
set
not set
set
not set
set

set
not set
set
not set
set
 
Last edited:
It occured to me the other night that it might be integers in PHP are signed, thus can only be -214<whatever> to (+)214<whatever>

Unsigned allow from 0 to (214<whatever> * 2)

but it might be completely wrong.
 
Back
Top Bottom