Skills101

AdvancedC Programming · Lesson 12 of 15 · Updated ·

Bitwise Operators in C — AND, OR, XOR, NOT, Shifts, Bit Masks and Bit-fields

Inside the computer, every integer is a row of bits (0s and 1s). Bitwise operators let you work on those bits one by one. They are used in device drivers, network code, compression and graphics — and in many placement questions such as "count the set bits" or "check if a number is a power of two".

1. Binary in one minute

Each bit position has a place value: from the right, 1, 2, 4, 8, 16, and so on. The number 12 in 8 bits is 00001100 because 8 + 4 = 12. The rightmost bit is bit 0.

A bit that is 1 is called set; a bit that is 0 is called clear.

2. The six bitwise operators

OperatorNameRule for each pair of bits
a & bAND1 only if both bits are 1
a | bOR1 if at least one bit is 1
a ^ bXOR1 if the bits are different
~aNOTflips every bit
a << nleft shiftmoves bits n places left, fills 0s on the right
a >> nright shiftmoves bits n places right

12 and 10 written in binary, with the results of AND (8), OR (14) and XOR (6) worked out bit by bit

#include <stdio.h>

int main(void) {
    int a = 12, b = 10;          /* 1100 and 1010 */
    printf("a & b  = %d\n", a & b);
    printf("a | b  = %d\n", a | b);
    printf("a ^ b  = %d\n", a ^ b);
    printf("~a     = %d\n", ~a);
    printf("a << 2 = %d\n", a << 2);
    printf("a >> 2 = %d\n", a >> 2);
    return 0;
}
a & b  = 8
a | b  = 14
a ^ b  = 6
~a     = -13
a << 2 = 48
a >> 2 = 3

Why is ~12 equal to -13? Integers are stored in two's complement, where -x is ~x + 1. So ~x is always -x - 1, and ~12 = -13.

Shifts multiply and divide by powers of two. a << n is a × 2ⁿ (12 × 4 = 48) and, for non-negative numbers, a >> n is a / 2ⁿ with the remainder dropped (12 / 4 = 3).

Use shifts only on non-negative values. Shifting a negative number left, or shifting by the width of the type or more (like 1 << 32 for a 32-bit int), is undefined behaviour. For bit work, unsigned int is the safest type.

3. Do not confuse & with &&

&& is logical AND: it treats each side as true or false and gives 1 or 0. & is bitwise AND: it works on each bit.

#include <stdio.h>

int main(void) {
    int a = 2, b = 4;            /* 010 and 100: no common bit */
    printf("%d %d\n", a && b, a & b);
    printf("%d %d\n", a || b, a | b);
    return 0;
}
1 0
1 6

Both 2 and 4 are "true", so a && b is 1. But they share no set bit, so a & b is 0.

4. Bit masks: set, clear, toggle, check

A mask is a number with 1s only in the positions you care about. 1u << k is a mask with only bit k set.

TaskExpressionWhy it works
set bit kx | (1u << k)OR with 1 makes it 1
clear bit kx & ~(1u << k)AND with 0 makes it 0
toggle bit kx ^ (1u << k)XOR with 1 flips it
check bit k(x >> k) & 1ubrings bit k to position 0

A real use: file permissions. Suppose bit 0 = read, bit 1 = write, bit 2 = execute.

#include <stdio.h>

#define READ  (1u << 0)
#define WRITE (1u << 1)
#define EXEC  (1u << 2)

void show(unsigned p) {
    printf("%c%c%c\n", (p & READ) ? 'r' : '-', (p & WRITE) ? 'w' : '-', (p & EXEC) ? 'x' : '-');
}

int main(void) {
    unsigned perm = READ;        /* r-- */
    show(perm);
    perm |= WRITE | EXEC;        /* set two bits */
    show(perm);
    perm &= ~WRITE;              /* clear write */
    show(perm);
    perm ^= READ;                /* toggle read */
    show(perm);
    return 0;
}
r--
rwx
r-x
--x

One unsigned holds many yes/no flags. This is exactly how Linux file permissions and many hardware registers work.

5. Classic interview programs

Count the set bits. The trick n & (n - 1) clears the lowest set bit, because subtracting 1 turns that 1 into 0 and every 0 to its right into 1. Each loop pass removes one set bit, so the loop runs only as many times as there are 1s (Brian Kernighan's method).

n = 44 is 101100; each step of n = n & (n - 1) clears the lowest set bit: 44 becomes 40, then 32, then 0, so 44 has 3 set bits

#include <stdio.h>

int count_bits(unsigned n) {
    int count = 0;
    while (n) {
        n &= n - 1;          /* remove the lowest 1 */
        count++;
    }
    return count;
}

int is_power_of_two(unsigned n) {
    return n != 0 && (n & (n - 1)) == 0;   /* exactly one bit set */
}

int main(void) {
    printf("%d %d %d\n", count_bits(44), count_bits(7), count_bits(0));
    printf("%d %d %d\n", is_power_of_two(64), is_power_of_two(48), is_power_of_two(1));
    return 0;
}
3 3 0
1 0 1

Odd or even. n & 1 is 1 for odd numbers and 0 for even numbers — the last bit decides.

XOR facts. x ^ x = 0 and x ^ 0 = x, and the order does not matter. So if every number appears twice except one, XOR-ing them all leaves the single one:

#include <stdio.h>

int main(void) {
    int a[] = {4, 7, 2, 7, 4};
    int ans = 0;
    for (int i = 0; i < 5; i++)
        ans ^= a[i];         /* pairs cancel out */
    printf("single = %d\n", ans);

    int x = 5, y = 9;        /* swap without a third variable */
    x ^= y; y ^= x; x ^= y;
    printf("x = %d, y = %d\n", x, y);
    return 0;
}
single = 2
x = 9, y = 5

The XOR swap is a popular interview trick, but in real code a temporary variable is clearer, and the XOR swap breaks if x and y are the same variable (it sets it to 0).

6. Printing a number in binary

printf has no binary format in standard C, so we check each bit from the top:

#include <stdio.h>

void print_binary(unsigned n, int bits) {
    for (int k = bits - 1; k >= 0; k--)
        putchar(((n >> k) & 1u) ? '1' : '0');
    putchar('\n');
}

int main(void) {
    print_binary(12, 8);
    print_binary(12 << 1, 8);
    print_binary(200, 8);
    return 0;
}
00001100
00011000
11001000

7. Bit-fields in structures

A bit-field lets a structure member use a chosen number of bits instead of a whole int. It is useful when memory is tight, for example storing a date.

#include <stdio.h>

struct date {
    unsigned day   : 5;      /* 0..31  needs 5 bits */
    unsigned month : 4;      /* 0..15  needs 4 bits */
    unsigned year  : 12;     /* 0..4095 */
};

int main(void) {
    struct date d = {26, 1, 1950};
    printf("%u/%u/%u\n", d.day, d.month, d.year);
    d.month = 13;                         /* fits in 4 bits, though not a real month */
    printf("month = %u\n", d.month);
    return 0;
}
26/1/1950
month = 13

The three fields use 21 bits, so the whole structure fits in one 4-byte unit on common compilers. The exact layout and size depend on the compiler. Rules to remember: you cannot take the address of a bit-field (&d.day is an error), and bit-fields cannot be arrays.

Common mistakes

  • Writing & when you meant && (or | for ||) in an if condition.
  • Forgetting brackets: x & 1 == 0 means x & (1 == 0), because == binds tighter than &. Write (x & 1) == 0.
  • Shifting negative numbers, or shifting by 32 or more on a 32-bit int.
  • Using ^ for "power" — 2 ^ 3 is 1 (XOR), not 8. Use 1 << 3 or pow.
  • Using the XOR swap on the same variable.

Quick recap

  • & both, | either, ^ different, ~ flip; << multiplies and >> divides by powers of two.
  • ~x == -x - 1 in two's complement.
  • Masks: set x | (1u << k), clear x & ~(1u << k), toggle x ^ (1u << k), check (x >> k) & 1.
  • n & (n - 1) removes the lowest set bit: count bits, test powers of two.
  • x ^ x == 0: find the single element, swap without a temporary.
  • Bit-fields pack small values into a few bits of a struct; no & on them.

Practice what you learned

📝 Quiz: Bitwise Operators in C5 questions · instant answers & explanations · +10 XP · counts towards your free certificateTake the quiz →