← 🔢 Types, Operators & Expressions
Subtopic 4 of 5

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

  1. Write both numbers in binary, aligned.
  2. Apply the operator column by column.
  3. Shift left by k: multiply by 2k. Shift right by k: divide by 2k (floor).
  4. 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.
a0010 1100= 44
b0001 1010= 26
a &0000 1000= 8
Tricks on a = 44
Expression8-bit resultWhat it does
a & (a − 1)00101000 = 40clears the lowest 1 bit
a & (−a)00000100 = 4keeps only the lowest 1 bit
a & 101 when a is odd
a ^ a0XOR of equal values is 0
number of 1 bits3repeat 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.

step 1 of 8
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)
main()
no variables yet
Output

Check yourself

What is 12 & 10?

Remember: & keeps common 1s, | merges, ^ marks differences; x & (x−1) clears the lowest 1 bit.
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.