TalentJR

⚙️ C programming basics · Class 10 · Lesson 17 of 18 · Free

Bitwise Operations in C – AND, OR, XOR, NOT and Shifts

⏱ About 35 minutes · ▶ run real C here — nothing to install · no sign-in

In this lesson you will

  • Use &, |, ^, ~, << and >> and predict their results in binary
  • Set, clear, toggle and check single bits with masks
  • Pack several yes/no options into one number with bit flags

A class register marks each day as present or absent. That is just yes or no, so one whole week fits in a single byte: 7 bits, one per day. Bitwise operators let C read and change those single bits, the same way device drivers, games and networks pack information tightly.

What are bitwise operators in C?

Every int is stored as bits: 0s and 1s. 5 is 0101 in binary (4 + 1). Bitwise operators work on each pair of bits separately.

& (AND) gives 1 only where BOTH bits are 1. | (OR) gives 1 where EITHER bit is 1. ^ (XOR, exclusive or) gives 1 where the bits are DIFFERENT. ~ (NOT) flips every bit.

print_bits shows the last few bits of a number. Try it: change a to 12 and b to 10, and check each line by hand.

⚙️ C — you can edit this code
Output
a      = 0101 = 5
b      = 0011 = 3
a & b  = 0001 = 1
a | b  = 0111 = 7
a ^ b  = 0110 = 6
~a     = 1010 (last 4 bits)

💡 Do not mix up & with && and | with ||: && and || give a single true/false (1 or 0) for the whole number.

How do left shift and right shift work in C?

x << n moves every bit n places to the left and fills with 0s. Each place doubles the value, so x << n is x × 2ⁿ.

x >> n moves bits to the right and drops the ones that fall off. For unsigned numbers that is x ÷ 2ⁿ, rounded down.

Use unsigned numbers for bit work. Shifting a negative number, or shifting by 32 or more places for a 32-bit int, is not fully defined in C. Try it: shift 1 left by 10 and get 1024.

⚙️ C — you can edit this code
Output
13 << 0 = 00001101 =  13
13 << 1 = 00011010 =  26
13 << 2 = 00110100 =  52
13 << 3 = 01101000 = 104
13 >> 1 = 00000110 =   6
13 >> 2 = 00000011 =   3
13 >> 3 = 00000001 =   1
1 << 5 = 32 (a number with only bit 5 on)

How do you set, clear, toggle and check a bit in C?

A mask is a number with just the bits you care about turned on. `1u << k` is a mask for bit k (bits are counted from 0 on the right).

Set bit k: x |= mask. Clear bit k: x &= ~mask. Toggle (flip) bit k: x ^= mask. Check bit k: (x & mask) != 0.

Here one byte holds a week of attendance: bit 0 is Monday, bit 6 is Sunday. Try it: mark Saturday (bit 5) present and run again.

⚙️ C — you can edit this code
Output
Mon: present
Tue: present
Wed: present
Thu: absent
Fri: present
Sat: absent
Sun: absent
Whole week as a number: 23

How do you use bit flags with enum in C?

Bit flags combine an enum (Lesson 10) with bits. Give each option its own bit: 1, 2, 4, 8 … Then one int can hold any mix of options.

Combine flags with |, and test one with &. This is how real C libraries pass options, for example when opening files on Linux.

Here a tiffin order stores its extras as flags. Try it: add a new flag PICKLE = 1 << 4 and order it.

⚙️ C — you can edit this code
Output
Order flags = 5, price Rs 90
Order flags = 3, price Rs 85
Has salad? no

What are some useful bit tricks in C?

n & 1 is the last bit, so it tells you if n is odd (1) or even (0). A power of two (1, 2, 4, 8 …) has exactly one bit on, so n & (n - 1) is 0 only for powers of two.

Counting the 1 bits is easy too: look at the last bit, shift right, repeat.

XOR has a neat property: (x ^ key) ^ key gives back x. That is the idea behind simple (but NOT secure) scrambling. Try it: change the key to 7.

⚙️ C — you can edit this code
Output
 7: odd, 3 one-bits, not a power of two
 8: even, 1 one-bits, power of two
12: even, 2 one-bits, not a power of two
64: even, 1 one-bits, power of two
Back again: MEET AT 4

💡 We do not print the scrambled text: some bytes may be odd, invisible characters.

🤔 Predict the output

Think like C: read the code and choose what it prints. You get the reason straight away.

Question 1. 6 is 110 and 3 is 011 in binary. What does this print?

printf("%d %d %d\n", 6 & 3, 6 | 3, 6 ^ 3);

Question 2. What does this print?

unsigned flags = 0;
flags |= 1u << 2;
flags |= 1u << 0;
flags &= ~(1u << 2);
printf("%u\n", flags);

Question 3. An unsigned char has 8 bits. What does this print?

unsigned char x = 5;
x = ~x;
printf("%d\n", x);

🧩 Your challenge

Read a week of attendance: 7 numbers (1 = present, 0 = absent) for Mon to Sun. Pack them into ONE unsigned char (bit 0 = Mon … bit 6 = Sun) using |= and shifts. Then use only the packed byte to print the bits (Sun on the left), the number of days present, and the absent days. Example for inputs 1 1 0 1 1 0 0: Bits (Sun..Mon): 0011011 Present: 4 days Absent: Wed Sat Sun

Expected output (with the inputs given):
Mon (1/0): 1
Tue (1/0): 1
Wed (1/0): 0
Thu (1/0): 1
Fri (1/0): 1
Sat (1/0): 0
Sun (1/0): 0
Bits (Sun..Mon): 0011011
Present: 4 days
Absent: Wed Sat Sun
⚙️ C — you can edit this code

⚠️ Common mistakes (and how to fix them)

❌ Wrong

int power = 2 ^ 3;
printf("2 to the power 3 = %d\n", power);

Compiles and runs, but prints: 2 to the power 3 = 1 ⏎

✅ Right

int power = 1 << 3;   /* or (int)pow(2, 3) */
printf("2 to the power 3 = %d\n", power);

In C, ^ is XOR, not "to the power of". 2 ^ 3 is 010 ^ 011 = 001, which is 1. Use 1 << n for powers of two, or pow() from <math.h>.

❌ Wrong

unsigned flags = 6, mask = 4;
if (flags & mask == 4) printf("bit is on\n");
else printf("bit is off\n");

Line 2: warning: & has lower precedence than ==; == will be evaluated first [-Wparentheses]

✅ Right

unsigned flags = 6, mask = 4;
if ((flags & mask) == 4) printf("bit is on\n");
else printf("bit is off\n");

== is done BEFORE &, so this means flags & (mask == 4). Always put brackets around a bitwise expression in a comparison. Clang warns you.

❌ Wrong

unsigned week = 31;          /* Mon to Fri present */
week &= (1u << 2);           /* try to clear Wed */
printf("%u\n", week);

Compiles and runs, but prints: 4 ⏎

✅ Right

unsigned week = 31;          /* Mon to Fri present */
week &= ~(1u << 2);          /* clear Wed */
printf("%u\n", week);

x &= mask keeps ONLY the masked bit and clears all the others. To clear one bit, AND with the flipped mask: x &= ~mask.

📌 Remember

  • & | ^ work bit by bit: AND both, OR either, XOR different; ~ flips every bit.
  • x << n multiplies by 2ⁿ and x >> n divides by 2ⁿ for unsigned numbers.
  • Set a bit with |= mask, clear with &= ~mask, toggle with ^= mask, check with & mask.
  • Bit flags (1, 2, 4, 8 …) pack many yes/no options into one number.
  • Use unsigned types and brackets around bitwise expressions; ^ is not power.

Finished the quiz and the challenge?

Questions students ask

What is the difference between & and && in C?

& works on every bit and gives a number: 6 & 3 is 2. && is logical AND: it treats each side as true or false and gives 1 or 0. Use && in if conditions and & for bit work.

Why use unsigned numbers for bitwise operations?

For unsigned numbers every shift and every bit pattern is fully defined by the C standard. With signed numbers, shifting negative values or shifting into the sign bit is not defined or depends on the compiler.

Is XOR encryption safe?

No. XOR with a short repeating key is easy to break. It is fine for learning how XOR works, but real security needs proper libraries and algorithms.

Where are bitwise operations used in real life?

In device drivers and microcontrollers (turning pins on and off), network addresses and masks, file permissions, graphics colours, compression and fast flags in games.