Example, a microcontroller has an 8 bit status register. Each bit controls some hardware function. You wish to change bit 5, but you can't change anything else because it would cause unwanted side effects. So this rules out simply saying myregister = 0b00001000.
Common solution is to make a macro like:
#define setbit(BYTE,BIT) BYTE |= (1 << BIT)
Thus you can say I want to set bit 5 in my register by calling setbit(foo, 5) while keeping the rest of the byte intact. There are analogous macros for clearing and toggling bits.
Or you might want to perform an operation based on a particular bit in a byte, e.g. byte 5 is a status flag that tells you when a timer has overflowed.
#define getbit(BYTE, BIT) !!(BYTE & ~(1 << BIT))
Then you can say:
if( getbit(myregister, 5)){ // do something }
Fun fun :)
- Interacting with hardware that uses certain bits in a register to control behavior - for example, Arduino digital ports [2]
- Doing arithmetic extra-fast with numbers that are powers of two - modulo becomes bitwise-and, division and multiplication become shifts
[1] http://en.wikipedia.org/wiki/List_of_monochrome_and_RGB_pale...
int FLAG_1 = 1;
int FLAG_2 = 2;
int FLAG_3 = 4; //These would actually probably be formatted like (1 << N)
...
And then pass in your options to a function like f(... FLAG_1+FLAG_2) so you can have an optional number of flags in a single argument.