php - Simple way to calculate values in a bitmask? -
apologies - i'm not sure i'm using right terminology here.
i have series of confidential documents , i'm creating bitmask (?) represent of documents given user can view. (1 represents doc1, 2 represents doc2, 4 represents doc3, 8 represents doc4, 16 represents doc5, etc.)
so, if user can view docs 1, 2, , 5, bitmask 19.
where i'm really stumped, though, how reverse calculate individual values "stored" in bitmask. currently, i'm using
if($docs2view==1) { $nextdoc = 1; } if($docs2view==2) { $nextdoc = 2; } . . . if($docs2view==127) { $nextdoc = 1; }
which tedious , inefficient. can point me toward right way this?
you need bitwise-and:
if( $docs2view & 1 ) {...} if( $docs2view & 2 ) {...} if( $docs2view & 4 ) {...} if( $docs2view & 8 ) {...} if( $docs2view & 16 ) {...}
here, i'm testing individual bits. if bit set, condition non-zero (hence evaluate 'true').
you possibly avoid lot of code repetition putting in loop , using bit-shift operators (>>
, <<
).
you said:
thank you, paddy! need lowest value evaluates true. how tell loop stop finds that?
you can either convert statements elseif
first becomes true, or can (assuming check first 8 bits):
$nextdoc = 0; for( $i = 0; $i < 8; $i++ ) { if( $docs2view & (1<<$i) ) { $nextdoc = $i + 1; break; } }
Comments
Post a Comment