How can I remove a flag in C?

前端 未结 3 1161
感动是毒
感动是毒 2020-12-12 10:23

There is a variable that holds some flags and I want to remove one of them. But I don\'t know how to remove it.

Here is how I set the flag.

my.emask          


        
3条回答
  •  醉酒成梦
    2020-12-12 10:42

    Short Answer

    You want to do an Bitwise AND operation on the current value with a Bitwise NOT operation of the flag you want to unset. A Bitwise NOT inverts every bit (i.e. 0 => 1, 1 => 0).

    flags = flags & ~MASK; or flags &= ~MASK;.

    Long Answer

    ENABLE_WALK  = 0    // 00000000
    ENABLE_RUN   = 1    // 00000001
    ENABLE_SHOOT = 2    // 00000010
    ENABLE_SHOOTRUN = 3 // 00000011
    
    value  = ENABLE_RUN     // 00000001
    value |= ENABLE_SHOOT   // 00000011 or same as ENABLE_SHOOTRUN
    

    When you perform a Bitwise AND with Bitwise NOT of the value you want unset.

    value = value & ~ENABLE_SHOOT // 00000001
    

    you are actually doing:

          0 0 0 0 0 0 1 1     (current value)
       &  1 1 1 1 1 1 0 1     (~ENABLE_SHOOT)
          ---------------
          0 0 0 0 0 0 0 1     (result)
    

提交回复
热议问题