Bit Manipulation in C
Every integer is stored as a row of bits (0s and 1s). Bit manipulation means reading or changing individual bits of a number using bitwise operators. It is used in device drivers, games, compression, networking and many interview questions.
In this lesson you will learn the four basic bit tricks (set, clear, toggle, check), how to build a mask, how to print a number in binary, and classic programs like counting set bits and checking for a power of 2. If the operators &, |, ^, ~, << and >> are new to you, first read Bitwise Operators in C.
What You Will Learn
- How bit positions are numbered.
- How to make a mask with
1 << n. - How to set, clear, toggle and check bit n.
- How to print the binary form of a number.
- How to count set bits and test for a power of 2.
- How to store several on/off options in one integer (bit flags).
Bit Manipulation in C Explained
Exam definition: Bit manipulation is the process of changing or testing individual bits of a value using bitwise operators and a mask, a value with 1s only in the positions of interest. For bit position n (counted from 0 at the right), the mask is 1 << n; then x | mask sets the bit, x & ~mask clears it, x ^ mask toggles it and x & mask tests it.
Memory trick: Think of a row of light switches. The mask points a finger at one switch. OR = "turn it ON", AND NOT = "turn it OFF", XOR = "flip it", AND = "look whether it is on". Easy rhyme: OR on, AND-NOT off, XOR flip, AND look.
Bit positions
Number 13 in 8 bits:
bit position : 7 6 5 4 3 2 1 0
bit value : 0 0 0 0 1 1 0 1
place value : 128 64 32 16 8 4 2 1 13 = 8 + 4 + 1
Mask for bit 2 = 1 << 2 = 0000 0100 = 4
Syntax: The Four Basic Bit Operations
x = x | (1 << n); /* SET bit n (make it 1) */
x = x & ~(1 << n); /* CLEAR bit n (make it 0) */
x = x ^ (1 << n); /* TOGGLE bit n (0->1, 1->0) */
(x >> n) & 1 /* CHECK bit n (gives 1 or 0) */
x & (1 << n) /* CHECK bit n (non-zero if set) */
/* Short forms */
x |= (1 << n);
x &= ~(1 << n);
x ^= (1 << n);
| Task | Expression | 13 (00001101), n = 1 |
|---|---|---|
| Set bit n | x | (1 << n) | 00001111 = 15 |
| Clear bit n | x & ~(1 << n) | 00001101 = 13 (already 0) |
| Toggle bit n | x ^ (1 << n) | 00001111 = 15 |
| Check bit n | (x >> n) & 1 | 0 |
Example 1: Set, Clear, Toggle and Check a Bit
#include <stdio.h>
void print_binary(unsigned int x)
{
int i;
for (i = 7; i >= 0; i--) /* show the lowest 8 bits */
{
printf("%u", (x >> i) & 1u);
if (i == 4)
printf(" ");
}
}
void show(const char *label, unsigned int x)
{
printf("%-15s = %3u = ", label, x);
print_binary(x);
printf("\n");
}
int main(void)
{
unsigned int x = 13; /* 0000 1101 */
show("x", x);
show("set bit 1", x | (1u << 1));
show("clear bit 2", x & ~(1u << 2));
show("toggle bit 0", x ^ (1u << 0));
show("toggle bit 7", x ^ (1u << 7));
printf("bit 3 is %u\n", (x >> 3) & 1u);
printf("bit 1 is %u\n", (x >> 1) & 1u);
return 0;
}
Output
x = 13 = 0000 1101 set bit 1 = 15 = 0000 1111 clear bit 2 = 9 = 0000 1001 toggle bit 0 = 12 = 0000 1100 toggle bit 7 = 141 = 1000 1101 bit 3 is 1 bit 1 is 0
Code Explanation
print_binaryshifts each bit to position 0 withx >> iand keeps only that bit with& 1, printing from bit 7 down to bit 0.- Set bit 1:
1u << 1= 0000 0010. OR with 0000 1101 gives 0000 1111 = 15. - Clear bit 2:
~(1u << 2)= 1111 1011. AND keeps every bit except bit 2: 0000 1001 = 9. - Toggle bit 0: XOR with 0000 0001 flips the last bit from 1 to 0: 12. Toggling bit 7 turns it on: 128 + 13 = 141.
- Check:
(13 >> 3) & 1= 1 (bit 3 is on),(13 >> 1) & 1= 0. - We use
unsigned intand1u, because shifting and inverting signed numbers can behave unexpectedly.
How the Bit Tricks Work
Each trick uses a property of one operator applied with a mask:
OR with 1 -> always 1 OR with 0 -> unchanged => SET
AND with 0 -> always 0 AND with 1 -> unchanged => CLEAR (use ~mask)
XOR with 1 -> flipped XOR with 0 -> unchanged => TOGGLE
AND with 1 -> shows bit AND with 0 -> 0 => CHECK
0000 1101 (13) 0000 1101 (13)
| 0000 0010 (mask, bit 1) & 1111 1011 (~mask, bit 2)
= 0000 1111 (15) = 0000 1001 (9)
Two more famous tricks:
n & (n - 1)removes the lowest set bit. 12 (1100) & 11 (1011) = 8 (1000). Son > 0 && (n & (n - 1)) == 0is true only for powers of 2 (they have exactly one set bit).n & 1is 1 for odd numbers and 0 for even numbers, a fast odd/even test.
Example 2: Count Set Bits, Power of 2 and Bit Flags
#include <stdio.h>
#define FLAG_BOLD (1u << 0) /* 0001 */
#define FLAG_ITALIC (1u << 1) /* 0010 */
#define FLAG_UNDERLINE (1u << 2) /* 0100 */
int count_set_bits(unsigned int n)
{
int count = 0;
while (n)
{
n &= n - 1; /* remove the lowest set bit */
count++;
}
return count;
}
int is_power_of_two(unsigned int n)
{
return n > 0 && (n & (n - 1)) == 0;
}
int main(void)
{
unsigned int nums[] = {13, 16, 255, 96};
unsigned int style = 0;
int i;
for (i = 0; i < 4; i++)
printf("%3u: set bits = %d, power of 2 = %s\n",
nums[i], count_set_bits(nums[i]), is_power_of_two(nums[i]) ? "yes" : "no");
style |= FLAG_BOLD | FLAG_UNDERLINE; /* turn on two options */
printf("style = %u\n", style);
printf("bold: %s, italic: %s, underline: %s\n",
(style & FLAG_BOLD) ? "on" : "off",
(style & FLAG_ITALIC) ? "on" : "off",
(style & FLAG_UNDERLINE) ? "on" : "off");
style &= ~FLAG_BOLD; /* turn bold off */
printf("after removing bold, style = %u\n", style);
return 0;
}
Output
13: set bits = 3, power of 2 = no 16: set bits = 1, power of 2 = yes 255: set bits = 8, power of 2 = no 96: set bits = 2, power of 2 = no style = 5 bold: on, italic: off, underline: on after removing bold, style = 4
count_set_bits(Brian Kernighan's method) loops once per set bit: 13 = 1101 needs 3 loops.- 16 = 10000 has one set bit, so it is a power of 2. 96 = 1100000 has two, so it isn't.
- Bit flags store several yes/no options in one number: bold (1) + underline (4) = 5. File permissions, keyboard modifiers and game settings often use this idea.
Important Points to Remember
- Bits are numbered from 0 at the right (least significant bit).
- Mask for bit n: 1 << n.
- Set =
|mask, clear =& ~mask, toggle =^mask, check =&mask. n & (n - 1)removes the lowest set bit; it is 0 for powers of 2.n & 1tells odd (1) or even (0).- Prefer unsigned types for bit work; shifting by the width of the type or more is undefined.
Common Mistakes Beginners Make
| Mistake | What happens | Fix |
|---|---|---|
x & 1 << n == 0 | == binds tighter than &, so it means x & ((1 << n) == 0) | Use brackets: (x & (1u << n)) == 0 |
Clearing with x & (1 << n) | Keeps only bit n, clears all others | x & ~(1 << n) |
| Counting bits from 1 | Every answer is off by one position | The rightmost bit is bit 0 |
1 << 31 on a 32-bit int | Signed overflow (undefined) | Use 1u << 31 |
Confusing && with & | Logical result 0/1 instead of bits | & for bits, && for conditions |
Bit Manipulation Practice Questions
- Write the expressions to set, clear, toggle and check bit n of x.
- What is a mask? What is the mask for bit 5?
- What is the result of
12 & 11, and what does it show? - How do you check whether a number is a power of 2 using bits?
- What is 6 after toggling bit 1?
Show answers
- Set:
x | (1 << n); clear:x & ~(1 << n); toggle:x ^ (1 << n); check:(x >> n) & 1. - A value with 1s only in the bit positions you want to work on; for bit 5 it is
1 << 5= 32. - 8 (1100 & 1011 = 1000);
n & (n - 1)removes the lowest set bit. n > 0 && (n & (n - 1)) == 0.- 6 = 110; toggling bit 1 gives 100 = 4.
Coding Exercise
Write a function unsigned int reverse_bits8(unsigned int x) that reverses the lowest 8 bits of x (bit 0 becomes bit 7, and so on). Test it with 1 (0000 0001), 13 (0000 1101) and 240 (1111 0000).
Show solution
#include <stdio.h>
unsigned int reverse_bits8(unsigned int x)
{
unsigned int result = 0;
int i;
for (i = 0; i < 8; i++)
{
result <<= 1; /* make room on the right */
result |= (x >> i) & 1u; /* copy bit i of x */
}
return result;
}
int main(void)
{
unsigned int tests[] = {1, 13, 240};
int i;
for (i = 0; i < 3; i++)
printf("%3u reversed = %3u\n", tests[i], reverse_bits8(tests[i]));
return 0;
}
1 reversed = 128 13 reversed = 176 240 reversed = 15
13 = 0000 1101 reversed is 1011 0000 = 176.
Quick Quiz: Bit Manipulation (MCQ)
-
Which expression sets bit 3 of x?
A)
x & (1 << 3)B)x | (1 << 3)C)x ^ 3D)x >> 3 -
Which operator toggles a bit?
A)
&B)|C)^D)~ -
What is
1 << 4?A) 4 B) 8 C) 16 D) 5
-
n & (n - 1)is 0 (for n > 0) when n is:A) Odd B) A power of 2 C) Prime D) Negative
-
How many set bits does 7 have?
A) 1 B) 2 C) 3 D) 7
Show answers
- B:
x | (1 << 3). - C:
^. - C: 16.
- B: a power of 2.
- C: 3 (111).
Quick Revision for Exams and Interviews
Read this before your exam. The highlighted words are the answer.
Must-remember facts
| Mask for bit n | 1 << n |
|---|---|
| Set | x | mask |
| Clear | x & ~mask |
| Toggle | x ^ mask |
| Check | (x >> n) & 1 |
| Power of 2 | n && !(n & (n - 1)) |
| Odd/even | n & 1 |
Frequently asked questions
- How do you check if the nth bit is set in C?
- Use (x >> n) & 1 (gives 1 or 0) or x & (1 << n) (non-zero if set).
- How do you count set bits in a number?
- Repeat n &= n - 1 until n is 0 and count the loops (Brian Kernighan's method).
- Why use bit flags?
- To store many on/off options in one integer, saving memory and making checks fast.
Remember
- OR on, AND-NOT off, XOR flip, AND look.
- Count bits from 0 at the right.
Next Topic
Next lesson: volatile Keyword in C. You will learn why some variables must be read from memory every time, and how volatile tells the compiler that.