Bitwise Operators

1-minute read
Table of Contents

There are six (6) bitwise operators in C:

  • Bitwise NOT/complement (~)
  • Bitwise AND (&)
  • Bitwise OR (|)
  • Bitwise XOR (^)
  • Left shift («)
  • Right shift (»)

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;
}
getting-each-bit.c
Copy

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

Support us via BuyMeACoffee