开发者

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

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. 开发者_高级运维So a=(1<<i) will not work.

a=a+(1<<i) will work,but I am looking for the fastest way. Anything??


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


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)


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.


You should use bitwise OR for this operation.

a |= 1 << i;


You could probably use

a |= (1 << i)

But it won't make much of a difference. Performance-wise, you shouldn't see any difference.

You might be able to try building a table where you map i to a bit mask (like 2 => 0x0010 for 0000000000100), but that's a bit unnecessary.


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜