Boolean algebra

In Boolean algebra, variables have only two values: true and false, usually denoted 1 and 0 respectively.

Four logical operations are widely used in programming:

  1. and or conjunction
  2. or or disjunction
  3. not or negation
  4. xor or exclusive or, this operation is a combination of three others
arg 1arg 2ANDXOROR NOT
E1E2E1 & E2E1 ^ E2 E1 | E2 !E1

bitwise operation

In programming sometimes the logic operations apply to the bits of number.

The bitwise NOT is a unary operation that performs logical negation on each bit. Bits that are 0 become 1, and those that are 1 become 0. It is also knows as inversion.

The bit shifts are operations where bits are moved to the left or right. In programming we have fixed number of bits, for example 32 or 64 bits. So some bits will be "shifted out" at one end, while the same number of bits are "shifted in" from the other end. When you are shifting to the left, the new bits are always zero. When you are shifting to the right, the new bits are zero for unsigned numbers and equal to the signed bit for signed numbers.

// example of using bitwise operations
private int f;

// clear all bits
void clear(){

// set bit i 
void set(int i, boolean val) {
    int k=1<<i; // shift 0 bit by i 

    // f=(val)?(f|k):(f&(~k)) or 

// get value of bit i
boolean isBit(int i) {
    return (f&(1<<i)) >0;
// C++
bool get(int i) {
    return f&(1<<i);