Categories

# Testing and setting individual bits

“Bit-twiddling”, or manipulating the individual bits of items such as integers, is sometimes considered to be a dark art used by advanced programmers. It’s true that setting individual bit values can seem a rather obscure procedure. But it can be useful, and it is a technique that is well worth knowing.

Let’s first discuss why you would want to do this. Programs often use “flag” variables to hold Boolean values (that is, true or false). So you might have a number of variables like these:

```int moving;
int decelerating;
int accelerating;
```

If these are related in some way, as the ones above are (they all define the state of some action related to movement), then it’s often more convenient to store all the information in a single “state variable” and use a single bit in that variable for each possible state, like this:

```#define MOVING (1 << 1)
#define DECELERATING (1 << 2)
#define ACCELERATING (1 << 3)
int state;
```

Then you can use bit-setting operations to set or clear an individual bit:

```state |= MOVING;
state &= ~MOVING;
```

The advantage is that all the state information is stored in one place and it’s clear that you are operating on a single logical entity.

The code archive contains an example that shows how to set, clear, and test a single bit in a integer. If you don’t understand exactly what is going on here, don’t worry. The best way to think of these are as standard “incantations.”

To set a given bit in an int called value (in the range 0 to 31), use this expression:

```value |= 1 << bit
```

To clear a given bit, use this:

```value &= ~(1 << bit);
```

And to test if a bit is zero or one, use this:

`r = value & (1 << bit);`