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.
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)
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.
You should use bitwise OR for this operation.
a |= 1 << i;
Bitwise or it. e.g. a |= (1<<i)
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.
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.