<p>Hey, in the Programming Pearls book, there is a source code for setting, clearing and testing a bit of the given index in an array of ints that is actually a set representation.</p>

<p>The code is the following:</p>

<pre><code>#include&lt;stdio.h&gt;
#define BITSPERWORD 32
#define SHIFT 5
#define MASK 0x1F
#define N 10000000

int a[1+ N/BITSPERWORD];

void set(int i)
{
    a[i&gt;&gt;SHIFT] |= (1&lt;&lt;(i &amp; MASK));
}

void clr(int i)
{
    a[i&gt;&gt;SHIFT] &amp;= ~(1&lt;&lt;(i &amp; MASK));
}

int test(int i)
{
    a[i&gt;&gt;SHIFT] &amp; (1&lt;&lt;(i &amp; MASK));
}
</code></pre>

<p>Could somebody explain me the reason of the SHIFT and the MASK defines? And what are their purposes in the code?</p>

<p>I've already read the previous related <a href="https://stackoverflow.com/questions/47981/how-do-you-set-clear-and-toggle-a-single-bit-in-c">question</a>.</p>

From
Here
(General answer to get this thread started)
A bit mask is a value (which may be stored in a variable) that enables you to isolate a specific set of bits within an integer type.
Normally the masked will have the bits you are interested in set to 1 and all the other bits set to 0. The mask then allows you to isolate the value of the bits, clear all the bits or set all the bits or set a new value to the bits.
Masks (particularly multi-bit ones) often have an associated shift value which is the amount the bits need shifting left so that the least significant masked bit is shifted to the least significant bit in the type.
For example using a 16 bit short data type suppose you wanted to be able to mask bits 3, 4 and 5 (LSB is number 0). You mask and shift would look something like
```
```
#define MASK 0x0038
#define SHIFT 3
```
```
Masks are often assigned in hexadecimal because it is easier to work with bits in the data type in that base as opposed to decimal. Historically octal has also been used for bit masks.
If I have a variable, var, that contains data that the mask is relevant to then I can isolate the bits like this
```
```
var & MASK
```
```
I can isolate all the other bits like this
```
```
var & ~MASK
```
```
I can clear the bits like this
```
```
var &= ~MASK;
```
```
I can clear all the other bits like this
```
```
var &= MASK;
```
```
I can set all the bits like this
```
```
var |= MASK;
```
```
I can set all the other bits like this
```
```
var |= ~MASK;
```
```
I can extract the decimal value of the bits like this
```
```
(var & MASK) >> SHIFT
```
```
I can assign a new value to the bits like this
```
```
var &= ~MASK;
var |= (newValue << SHIFT) & MASK;
```
```