vipin
vipin

Reputation: 1660

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??

Upvotes: 5

Views: 12994

Answers (7)

SE Does Not Like Dissent
SE Does Not Like Dissent

Reputation: 1825

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.

Upvotes: 1

Brandon E Taylor
Brandon E Taylor

Reputation: 25339

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)

Upvotes: 9

Paul R
Paul R

Reputation: 212949

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.

Upvotes: 3

Luke
Luke

Reputation: 7210

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.

Upvotes: 1

Joe
Joe

Reputation: 57169

You should use bitwise OR for this operation.

a |= 1 << i;

Upvotes: 2

derekerdmann
derekerdmann

Reputation: 18252

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.

Upvotes: 1

Matt K
Matt K

Reputation: 13842

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

Upvotes: 11

Related Questions