![[Dept of Engineering]](http://www.eng.cam.ac.uk/images/house_style/engban-s.gif)
Next: Using routines from other
Up: Specialist Areas
Previous: Maths
If you're interfacing with hardware and need to operate on bits you
can use bitset but you may prefer to use C++'s low-level operations.
- 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 :-
- 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. For example, 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 ;
Suppose because of hardware considerations the i variable
needed to be the value of memory location 2000. The following code
will do what you want.
long *memory_pointer = reinterpret_cast<long*>(2000);
long i = *memory_pointer;
Next: Using routines from other
Up: Specialist Areas
Previous: Maths
Tim Love
2001-07-05