Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set a specific bit in an int

People also ask

How do you set a certain bit in a number?

To set any bit we use bitwise OR | operator. As we already know bitwise OR | operator evaluates each bit of the result to 1 if any of the operand's corresponding bit is set (1).

How do you set a bit?

Setting a bit means that if K-th bit is 0, then set it to 1 and if it is 1 then leave it unchanged. Clearing a bit means that if K-th bit is 1, then clear it to 0 and if it is 0 then leave it unchanged. Toggling a bit means that if K-th bit is 1, then change it to 0 and if it is 0 then change it to 1.

How do you mask a bit?

Masking is the act of applying a mask to a value. This is accomplished by doing: Bitwise ANDing in order to extract a subset of the bits in the value. Bitwise ORing in order to set a subset of the bits in the value.

How do I change bits in Java?

b = (byte) (b | (1 << 6)); To set the sixth bit to zero: b = (byte) (b & ~(1 << 5));


If you have an int value "intValue" and you want to set a specific bit at position "bitPosition", do something like:

intValue = intValue | (1 << bitPosition);

or shorter:

intValue |= 1 << bitPosition;


If you want to reset a bit (i.e, set it to zero), you can do this:

intValue &= ~(1 << bitPosition);

(The operator ~ reverses each bit in a value, thus ~(1 << bitPosition) will result in an int where every bit is 1 except the bit at the given bitPosition.)


To set everything to 0, AND the value with 0x00000000:

int startValue = initialValue & 0x00000000;
//Or much easier :)
int startValue = 0;

To then set the bit, you have to determine what number has just that bit set and OR it. For example, to set the last bit:

int finalValue = startValue | 0x00000001;

As @Magus points out, to unset a bit you do the exact opposite:

int finalValue = startValue & 0xFFFFFFFE;
//Or
int finalValue = startValue & ~(0x00000001);

The ~ operatior is bitwise not which flips every bit.


so, this?

enum ConditionEnum 
{
    Aaa = 0,
    Bbb = 1,
    Ccc = 2,
}    

static void SetBit(ref int bitFlag, ConditionEnum condition, bool bitValue)
{
    int mask = 1 << (int)condition;
    if (bitValue)
        bitFlag |= mask;
    else
        bitFlag &= ~mask;
}