C & PHP: Storing settings in an integer using bitwise operators?

后端 未结 3 863
醉梦人生
醉梦人生 2020-12-14 09:57

I\'m not familiar with bitwise operators, but I have seem them used to store simple settings before.

I need to pass several on/off options to a function, and I\'d li

3条回答
  •  执笔经年
    2020-12-14 10:24

    quote "the idea is not good, really. you would better pass few boolean. if you want use bitwise then

    function someFunc($options)
    {
    
       if ($options & 1 != 0)
          //then option 1 enabled
       if ($options & (1 << 1) != 0)
          //then option 2 enabled      
       if ($options & (1 << 2) != 0)
          //then option 3 enabled      
    }
    

    "

    What you have done would be okay if you were checking for a single value, although not optimal, so checking that a bit is enabled, but lets say we wanted to be able to match any, or exact we could have the following methods

    function matchExact($in, $match) { // meets your criterion, as would a switch, case, but ultimately not suited for use with flags
        return $in === $match;
    }
    
    function matchAny($in, $match) { // meets original criterion with more lexical name however it returns true if any of the flags are true
        return $in |= $match;
    }
    

    if you then wanted to expand upon this by having specific actions only happening if bit x,y,z was enabled then you could use the following

    function matchHas($in, $match) { // more bitwise than === as allows you to conditionally branch upon specific bits being set
        return $in &= $match;
    }
    

    I also think if you are doing what was done in the above quote, flags may not be the best idea, exact values might be better, which does have the benefit of allowing more discreet actions. (0-255) for 8-bit over 8 distinct flags

    The whole reason flags work so well is because in base 2 "8" does not contain "4", and "2" does not contain "1".

     ________________________
     |8|4|2|1|Base 10 Value |
     ------------------------
     |1|1|1|1|15            |
     |1|1|1|0|14            |
     |1|1|0|1|13            |
     |1|1|0|0|12            |
     |1|0|1|1|11            |
     |1|0|1|0|10            |
     |1|0|0|1|9             |
     |1|0|0|0|8             |
     |0|1|1|1|7             |
     |0|1|1|0|6             |
     |0|1|0|1|5             |
     |0|1|0|0|4             |
     |0|0|1|1|3             |
     |0|0|1|0|2             |
     |0|0|0|1|1             |
     |0|0|0|0|0             |
     ------------------------
    

提交回复
热议问题