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

Consider a variable unsigned int a;in C.

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

Note that the variable has some meaning. Therefore, a=(1<<i)it will not work.

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

+5
source share
7 answers

Bitwise or this. ega |= (1<<i)

+10
source

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)
+6
source

:

a |= (1 << i);

- OR. , .

+3

.

a |= 1 << i;
+2

,

a |= (1 << i)

. , .

, , i (, 2 = > 0x0010 0000000000100), .

+1

:

a |= (1 << i);

, , +, , 1.

+1

, - ( , , ):

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));
}

.

You may need to remove or modify the code to use the specific set of variables that you are using, but it should normally work fine.

+1
source

All Articles