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
- Table of Contents
- 12.1 Bitwise Operators
- 12.2 Common Bitwise Tricks
- 12.3 Exercises
- 12.4 Solutions
- 12.5 What’s Coming in the Next Chapter
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
- Write a program to check if a number is even using bitwise AND.
- Swap two numbers using XOR.
- 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!
This post is licensed under CC BY 4.0 by the author.