Snippet:Bitwise operations

From Curuxa

This is a collection of common operations done with individual bits in variables.

Set/clear bits

#include <pic16fxxx.h>
 
#define SetBit(v,bit) v |= (1 << bit);
#define ClearBit(v,bit) v &= ~(1 << bit);
 
// more things...
 
void main() {
    int a = 1;
    SetBit(a, 2);
    // now "a" is 5 (decimal), 00000101 (binary)
    ClearBit(a, 0);
    // now "a" is 4 (decimal), 00000100 (binary)
}