Most efficient way to extract bit flags

后端 未结 5 723
旧巷少年郎
旧巷少年郎 2021-01-02 10:08

I have these possible bit flags.

1, 2, 4, 8, 16, 64, 128, 256, 512, 2048, 4096, 16384, 32768, 65536

So each number is like a true/false sta

5条回答
  •  北海茫月
    2021-01-02 11:08

    Thought the question is old might help someone else. I am putting the numbers in binary as its clearer to understand. The code had not been tested but hope the logic is clear. The code is PHP specific.

    define('FLAG_A', 0b10000000000000);  
    define('FLAG_B', 0b01000000000000);
    define('FLAG_C', 0b00100000000000);
    define('FLAG_D', 0b00010000000000);
    define('FLAG_E', 0b00001000000000);
    define('FLAG_F', 0b00000100000000);
    define('FLAG_G', 0b00000010000000);
    define('FLAG_H', 0b00000001000000);
    define('FLAG_I', 0b00000000100000);
    define('FLAG_J', 0b00000000010000);
    define('FLAG_K', 0b00000000001000);
    define('FLAG_L', 0b00000000000100);
    define('FLAG_M', 0b00000000000010);
    define('FLAG_N', 0b00000000000001);
    
    function isFlagSet($Flag,$Setting,$All=false){
      $setFlags = $Flag & $Setting;
      if($setFlags and !$All) // at least one of the flags passed is set
         return true;
      else if($All and ($setFlags == $Flag)) // to check that all flags are set
         return true;
      else
         return false;
    }
    

    Usage:

    if(isFlagSet(FLAG_A,someSettingsVariable)) // eg: someSettingsVariable = 0b01100000000010
    
    if(isFlagSet(FLAG_A | FLAG_F | FLAG_L,someSettingsVariable)) // to check if atleast one flag is set
    
    if(isFlagSet(FLAG_A | FLAG_J | FLAG_M | FLAG_D,someSettingsVariable, TRUE)) // to check if all flags are set
    

提交回复
热议问题