Post

Chapter 12: Bitwise Operations – Ones, Zeros, and Mind Tricks

Master bitwise operations in C.

Chapter 12: Bitwise Operations – Ones, Zeros, and Mind Tricks

Table of Contents

12.1 Bitwise Operators

  • & AND
  • | OR
  • ^ XOR
  • ~ NOT
  • << left shift
  • >> right shift

Example:

1
int a = 5 & 3; // AND

12.2 Common Bitwise Tricks

  • Swapping values
  • Checking even/odd
  • Setting/clearing bits

12.3 Exercises

  1. Write a program to check if a number is even using bitwise AND.
  2. Swap two numbers using XOR.
  3. What does ~0 evaluate to?

12.4 Solutions

12.4.1 Solution 1

1
if ((x & 1) == 0) printf("Even\n");

12.4.2 Solution 2

1
2
3
a = a ^ b;
b = a ^ b;
a = a ^ b;

12.4.3 Solution 3

All bits set (bitwise NOT of 0).

12.5 What’s Coming in the Next Chapter

Next, you’ll learn about C libraries and header files!

Next Chapter → C Libraries and Header Files

This post is licensed under CC BY 4.0 by the author.