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

前端 未结 7 1274
再見小時候
再見小時候 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: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.

提交回复
热议问题