1.4Bitwise operators and shifts
The idea
Bitwise operators work on every bit of the numbers at once: & (both 1), | (either 1), ^ (different), ~ (flip). Shifts slide the bits.
Think of it like this: Two rows of light switches: AND keeps a light only if both switches are on, OR if either is on, XOR if exactly one is on.
Why it exists
GATE applies these to ASCII codes and counts bits (x & (x−1)), so you must do them in binary quickly.
How it works
- Write both numbers in binary, aligned.
- Apply the operator column by column.
- Shift left by k: multiply by 2k. Shift right by k: divide by 2k (floor).
- Convert back to decimal or to a character before printing.
Worked example: 'P' & 'x'
'P' = 80 = 01010000 and 'x' = 120 = 01111000. AND gives 01010000 = 80. Adding '*' (42) gives 122 = 'z', which is how the GATE 2022 program starts to print z K S.
Now play with it
- →Use the lab with a = 80, b = 120 and operator &.
- →Try the a & (a − 1) row for different a and watch the lowest 1 bit disappear.
Tricks on a = 44
| Expression | 8-bit result | What it does |
|---|---|---|
| a & (a − 1) | 00101000 = 40 | clears the lowest 1 bit |
| a & (−a) | 00000100 = 4 | keeps only the lowest 1 bit |
| a & 1 | 0 | 1 when a is odd |
| a ^ a | 0 | XOR of equal values is 0 |
| number of 1 bits | 3 | repeat a &= a − 1 until 0 and count |
ASCII: P = 80 (01010000), x = 120 (01111000). AND, OR and XOR are applied to the codes, then a constant is added.
1#include <stdio.h>2int main() {3 char a = 'P';4 char b = 'x';5 char c = (a & b) + '*';6 char d = (a | b) - '-';7 char e = (a ^ b) + '+';8 printf("%c %c %c\n", c, d, e);9 return 0;10}
The gold line is the statement about to run.
Call stack (top first)
Output
Check yourself
What is 12 & 10?
Exam notes (the dense version)
& | ^ ~ act on every bit; x << k multiplies by 2k, x >> k divides by 2k (rounding toward −∞ for negative signed values in practice). Useful tricks: x & (x−1) clears the lowest 1 bit, x & −x isolates it, x & 1 tests odd, x ^ x = 0. & is not &&, and ^ is XOR, not power.
Previous year questions: Types, Operators & Expressions (2)
PYQs are grouped by topic, so this is the full set for Types, Operators & Expressions; try the ones that match this subtopic. Open all 2 on the topic page.