What is the best way to set a particular bit in a variable in C

前端 未结 7 1271
再見小時候
再見小時候 2021-01-18 19:02

Consider a variable unsigned int a; in C.

Now say I want to set any i\'th bit in this variable to \'1\'.

Note that the variable has some value.

相关标签:
7条回答
  • 2021-01-18 19:41

    Some useful bit manipulation macros

    #define BIT_MASK(bit)             (1 << (bit))
    #define SET_BIT(value,bit)        ((value) |= BIT_MASK(bit))
    #define CLEAR_BIT(value,bit)      ((value) &= ~BIT_MASK(bit))
    #define TEST_BIT(value,bit)       (((value) & BIT_MASK(bit)) ? 1 : 0)
    
    0 讨论(0)
  • 2021-01-18 19:42

    You could use a bitwise OR:

    a |= (1 << i);
    

    Note that this does not have the same behavior as +, which will carry if there's already a 1 in the bit you're setting.

    0 讨论(0)
  • 2021-01-18 19:48

    You should use bitwise OR for this operation.

    a |= 1 << i;
    
    0 讨论(0)
  • 2021-01-18 19:51

    Bitwise or it. e.g. a |= (1<<i)

    0 讨论(0)
  • 2021-01-18 19:52

    The way I implemented bit flags (to quote straight out of my codebase, you can use it freely for whatever purpose, even commercial):

    void SetEnableFlags(int &BitFlags, const int Flags)
    {
        BitFlags = (BitFlags|Flags);
    }
    const int EnableFlags(const int BitFlags, const int Flags)
    {
        return (BitFlags|Flags);
    }
    
    void SetDisableFlags(int BitFlags, const int Flags)
    {
        BitFlags = (BitFlags&(~Flags));
    }
    const int DisableFlags(const int BitFlags, const int Flags)
    {
        return (BitFlags&(~Flags));
    }
    

    No bitwise shift operation needed.

    You might have to tidy up or alter the code to use the particular variable set you're using, but generally it should work fine.

    0 讨论(0)
  • 2021-01-18 19:56

    The most common way to do this is:

    a |= (1 << i);
    

    This is only two operations - a shift and an OR. It's hard to see how this might be improved upon.

    0 讨论(0)
提交回复
热议问题