## With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

No credit card required

# 3.10. Turning Bits On or Off

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

## Discussion

When a large number of flags are required, and particularly when combinations of flags can be set, it becomes cumbersome and unwieldy to use Boolean variables. In this case, using the binary representation of a number, we can assign each bit to indicate a specific Boolean value. Each Boolean value is called a bit flag. For example, we have a number defined as a `byte` data type. This number is comprised of eight binary bit values, which can be either a `1` or a `0`. Supposing we assign a color to each bit, our number would be defined as follows:

`byte colorValue = 0; // colorValue initialized to no color // colorValue Bit position // red 0 (least-significant bit) // green 1 // blue 2 // black 3 // grey 4 // silver 5 // olive ...`

## With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

No credit card required