Turning Bits On or Off

15 Aug 2017

code

Original article

JIC copy

Problem

You have a numeric value or an enumeration that contains bit flags. You need a method to turn on (set the bit to 1) or turn off (set the bit to 0) one or more of these bit flags. In addition, you also want a method to flip one or more bit flag values; that is, change the bit(s) to their opposite value.

Solution

The following method turns one or more bits on:

public static int TurnBitOn(int value, int bitToTurnOn)
{
    return (value | bitToTurnOn);
}

The following method turns one or more bits off:

public static int TurnBitOff(int value, int bitToTurnOff)
{
    return (value & ~bitToTurnOff);
}

The following method flips a bit to its opposite value:

public static int FlipBit(int value, int bitToFlip)
{
    return (value ^ bitToFlip);
}

Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.