Department of Engineering

Next: Declarations Up: Keywords, Operators and Declarations Previous: Operators   Contents

## Bit operations

C can be used to operate on bits. This is useful for low-level programming though the operations are also used when writing graphics applications.

Setting a bit :-
Suppose you wanted to set bit 6 of i (a long, say) to 1. First you need to create a mask that has a 1 in the 6th bit and 0 elsewhere by doing ``1L<<6`' which shifts all the bits of the long 1 left 6 bits. Then you need to do a bit-wise OR using ``i = i | (1L<<6)`'.

Unsetting a bit :-
Suppose you wanted to set bit 6 of i (a long, say) to 0. First you need to create a mask that has a 0 in the 6th bit and 1 elsewhere by doing ``1L<<6`' then inverting the bits using the `~` operator. Then you need to do a bit-wise AND using the `&` operator. The whole operation is ``i =i & ~(1<<6)`' which can be contracted to ``i &= ~(1<<6)`'.

Creating a mask for an call :-
In graphics, masks are often created each of whose bits represent a option that is to be selected in some way. Each bit can be referred to using an alias that has been set up in an include file. E.g. a mask which could be used in a call to make a window sensitive to key presses and buttonpresses could be set up by doing
```unsigned int mask = KeyPressMask | ButtonPressMask;
```

Next: Declarations Up: Keywords, Operators and Declarations Previous: Operators   Contents
Tim Love 2010-04-27