c > math > bitwise operators

Bitwise Operators

There are six (6) bitwise operators in C:

Bit shifting

We can use the << and >> operators to bit shift a number. Left shifting a number by 1 digit is the same as multiplying that number by 2. Right shifting the number by 1 digit is the same as an integer division by 2 (dividing by 2 and rounding the result downwards).

We can use the right shift and a logical AND to access each bit in a number:


#include <stdio.h>

int main(){
    int number = 8;
    for (int i=0;i<number;i++){
        printf("%d in binary: %d %d %d\n",i,i>>2&1,i>>1&1,i&1);
    }
    return 0;
}

↗ Open 📋 Copy c/math/getting_each_bit.c

Doing a logical AND with a number gives us the rightmost bit.