문제

Apologies - I'm not even sure I'm using the right terminology here.

I have a series of confidential documents and I'm creating a bitmask (?) to represent which of those documents a given user can view. (1 represents Doc1, 2 represents Doc2, 4 represents Doc3, 8 represents Doc4, 16 represents Doc5, etc.)

So, if a user can view docs 1, 2, and 5, the bitmask will be 19.

Where I'm really stumped, though, is how to reverse calculate the individual values "stored" in the bitmask. Currently, I'm using

if($docs2view==1) {
    $nextdoc = 1;
}
if($docs2view==2) {
    $nextdoc = 2;
}
. . .
if($docs2view==127) {
    $nextdoc = 1;
}

which is REALLY tedious and obviously very inefficient. Can someone point me toward the right way to do this?

도움이 되었습니까?

해결책

You need a bitwise-and:

if( $docs2view & 1 ) {...}
if( $docs2view & 2 ) {...}
if( $docs2view & 4 ) {...}
if( $docs2view & 8 ) {...}
if( $docs2view & 16 ) {...}

Here, I'm testing individual bits. If the bit is set, the condition will be non-zero (hence will evaluate to 'true').

You could possibly avoid a lot of code repetition by putting this in a loop and using the bit-shift operators (>> and <<).


You said:

Thank you, paddy! But I only need the lowest value that evaluates true. How do I tell the loop to stop as soon as it finds that?

You can either convert those statements to elseif so that only the first becomes true, or you can do this (assuming you only check the first 8 bits):

$nextdoc = 0;

for( $i = 0; $i < 8; $i++ ) {
    if( $docs2view & (1<<$i) ) {
        $nextdoc = $i + 1;
        break;
    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top