let's in system users' statuses assigned numbers powers of 2.
1 - new member 2 - member 4 - friend 8 - vip 16 - admin 32 - system owner
so if system owner
got friend
, admin
statuses, status have value of 52. now, want query status table , see users have friend
status. how check number 4
part of number-generating sum (52
)?
if done function, following output expected:
ispartof( 4, 52); //returns true ispartof(12, 52); //returns false since 8 (vip) not used during calculating 52
algorithm comes mind subtraction of maximum possible number (2^n) lower (in example case) 52
. there more efficient way this?
bitwise and.
>>> 52 & 4 == 4 true >>> 52 & 12 == 12 false
Comments
Post a Comment