Set a specific bit in an int

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.)

Leave a Comment