Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 135 ยท Operators

Bitwise Operators

Learn C's bitwise operators & | ^ ~ << >>: print binary, build masks, set, clear and toggle bits, pack flags, avoid undefined shifts, and use C23 stdbit.h.

Underneath every integer is a row of bits. Usually you think of 45 as a number, but sometimes the individual ones and zeros are the data: eight on/off settings packed into one byte, the red, green and blue channels of a color, the permission bits of a file, the fields in a network packet header or a hardware register on a microcontroller. C was designed for writing operating systems, so it gives you direct access to bits through six bitwise operators, and they compile to single machine instructions.

In this lesson you'll learn to read binary, apply &, |, ^, ~, << and >>, and use the four everyday operations: test, set, clear and toggle a bit. You'll also learn the rules that make some shifts undefined, why ~ surprises people on small types, and what C23's <stdbit.h> adds.

Reading binary

Each bit position stands for a power of two. Bit 0, the rightmost, is worth 1; bit 1 is worth 2; bit 2 is worth 4; and so on:

TEXT
bit position:   7   6   5   4   3   2   1   0
worth:        128  64  32  16   8   4   2   1
45 in binary:   0   0   1   0   1   1   0   1   = 32 + 8 + 4 + 1

C23 lets you write that directly as a binary literal, 0b00101101, and digit separators make long ones readable: 0b0010'1101. Older code uses hexadecimal instead, where each hex digit is exactly four bits: 0x2D is 0010 1101.

C23 also adds a %b conversion to printf, but it needs a recent C library, and the one on our server prints a literal %b instead. The examples in this lesson therefore use a small helper that prints the bits of a byte, one at a time. It already uses the operators you're about to learn:

C
void print_bits(unsigned char value) {
    for (int bit = 7; bit >= 0; bit--) {
        putchar((value >> bit) & 1 ? '1' : '0');
    }
}

Do bit work on unsigned types: unsigned int, unsigned char, or the fixed-width types uint8_t, uint16_t, uint32_t and uint64_t from <stdint.h> (see Integer Types). Their bits mean exactly what they look like, shifts never involve a sign bit, and overflow wraps instead of being undefined.

The six bitwise operators

Operator Name Each result bit is 1 whenโ€ฆ
a & b AND both bits are 1
a | b OR at least one bit is 1
a ^ b XOR (exclusive or) the two bits differ
~a NOT (one's complement) the bit was 0: every bit flips
a << n left shift bits move n places left, zeros fill in from the right
a >> n right shift bits move n places right

&, | and ^ work column by column: bit 0 of a with bit 0 of b, bit 1 with bit 1, and so on. Each binary operator has a compound form: &=, |=, ^=, <<=, >>= (see Assignment and Increment Operators).

C The bitwise operators bit by bit

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Look at a << 1: the top bit of a falls off the end once the result is stored back into eight bits, which is why the value is 148 and not 404. The casts to unsigned char are explained in "Promotion and the ~ trap" below.

Masks: test, set, clear and toggle

A mask is a value with ones in exactly the positions you care about. A mask for bit n is 1u << n (the u makes it unsigned). With it, each everyday operation is one line:

Goal Code Why it works
Test bit n (x & (1u << n)) != 0 AND keeps only that bit
Set bit n x |= 1u << n OR with 1 forces a 1
Clear bit n x &= ~(1u << n) AND with 0 forces a 0; ~ gives all ones except bit n
Toggle bit n x ^= 1u << n XOR with 1 flips the bit

Masks can cover several bits at once. x & 0x0F keeps the low four bits (the low "nibble"), and (x >> 4) & 0x0F extracts the high four. The same "shift down, then mask" pattern pulls fields out of any packed value, such as a color stored as 0xRRGGBB:

C Set, clear, toggle and extract bits

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Building a packed value is the reverse: shift each part into its position and combine the parts with |. Since the parts don't overlap, | and + would give the same result here, but | says "combine bits" more clearly.

Flags: many yes/no values in one integer

A set of options fits neatly into one integer, one bit per option. You define each option as a power of two, combine them with |, and test them with &. Unix file permissions are the best-known example: read is 4, write is 2, execute is 1, so chmod 750 means owner 7 (read, write, execute), group 5 (read, execute), others 0.

C Permission flags

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Note the last test: (group & needed) == needed checks that all the needed bits are set, while (group & needed) != 0 would only check that any of them is. An enum or #define for each flag keeps the bit positions in one place; the Enumerations lesson covers enum flags in more depth, and Bit-Fields shows another way to pack flags into a struct.

Promotion and the ~ trap

Bitwise operators follow the same integer promotion rule as arithmetic (see Arithmetic Operators): an unsigned char or uint8_t operand is converted to int first. For &, | and ^ that rarely matters, but ~ flips all 32 bits of the promoted int, so the upper bits that were zeros become ones. The result is a negative int, not the 8-bit value you pictured. This example compiles with a warning on purpose:

C Why ~ on a small type needs a cast

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

GCC spots this exact mistake: comparison of promoted bitwise complement of an unsigned value with constant. Cast the result back to the small type, or do the work in unsigned int from the start. ~0u is a handy way to get an unsigned value with every bit set.

Shift rules and undefined behavior

For unsigned values, x << n is the same as multiplying by 2โฟ (bits pushed off the top are lost) and x >> n is the same as dividing by 2โฟ and rounding down. Compilers already turn x * 8 into a shift when that's faster, so write whichever expresses your intent better.

Shifts have sharp edges, and these rules still hold in C23:

  1. The shift count must be at least 0 and less than the width of the promoted left operand. Shifting a 32-bit value by 32 or more, or by a negative count, is undefined. 1 << 40 is a bug, because 1 is a 32-bit int; write 1ULL << 40 or (uint64_t)1 << 40. With a constant count, GCC warns: left shift count >= width of type.
  2. Left-shifting a negative value, or shifting a 1 into or past the sign bit of a signed type, is undefined. 1 << 31 with a 32-bit int is undefined in C; 1u << 31 is fine.
  3. Right-shifting a negative value is implementation-defined. GCC and Clang copy the sign bit (an arithmetic shift), so -16 >> 2 is -4 there, but the standard doesn't promise it, and it's not the same as dividing: -7 >> 1 is -4 with GCC while -7 / 2 is -3.
C
uint64_t big = 1ULL << 40;    // OK: 1099511627776
uint32_t top = 1u << 31;      // OK: 2147483648
int bad = 1 << 31;            // undefined: shifts into the sign bit of int
uint32_t worse = 1u << 32;    // undefined: count equals the width (GCC warns)

The rule of thumb is short: shift unsigned values by counts smaller than their width. Then shifts always do exactly what the table above says.

Classic bit tricks

You'll meet these in performance-sensitive code and in interviews. All assume an unsigned x:

  • x & 1 is 1 for odd numbers and 0 for even ones.
  • x & (x - 1) clears the lowest set bit. It's zero exactly when x is 0 or a power of two.
  • x & -x (or x & (~x + 1)) isolates the lowest set bit.
  • a ^ a is 0, and a ^ b ^ b is a again: the basis of simple checksums, parity and the "find the value that appears once" puzzle.
C Counting bits and spotting powers of two

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The old XOR swap (a ^= b; b ^= a; a ^= b;) avoids a temporary variable, but it's harder to read, usually slower than an ordinary swap on modern CPUs, and it zeroes the value if both names refer to the same variable. Use a temporary.

C23: the stdbit.h header

Counting bits and finding the highest set bit are so common that C23 adds a standard header for them, <stdbit.h>. Its functions accept any unsigned integer type through type-generic names such as stdc_count_ones, stdc_leading_zeros, stdc_trailing_zeros, stdc_has_single_bit, stdc_bit_width, stdc_bit_floor and stdc_bit_ceil:

C
#include <stdbit.h>   // C23: needs glibc 2.39+ or another recent C library

unsigned int x = 44;                       // 0010 1100
unsigned ones = stdc_count_ones(x);        // 3
bool single = stdc_has_single_bit(x);      // false
unsigned width = stdc_bit_width(x);        // 6
unsigned trailing = stdc_trailing_zeros(x);// 2

The header comes with the C library, not the compiler, so it isn't available everywhere yet, including on our server. Until it is, GCC and Clang offer non-standard built-ins such as __builtin_popcount(x), __builtin_clz(x) and __builtin_ctz(x) (the last two are undefined for 0). They work only with those compilers, so wrap them in a function of your own, or use a portable loop like count_bits above.

Precedence pitfalls

The bitwise operators bind more loosely than comparisons, a decision from C's early days that its own designers later regretted. So this line is wrong:

C
if (flags & MASK == 0)       // parsed as flags & (MASK == 0)
if ((flags & MASK) == 0)     // what you meant

GCC warns with -Wall: suggest parentheses around comparison in operand of '&'. Shifts also bind more loosely than + and -, so 1 << n + 1 means 1 << (n + 1). And remember that & and | don't short-circuit like && and || (see Comparison and Logical Operators). With bits, use parentheses generously; the full table is in Operator Precedence.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is 0x0C ^ 0x0A (binary 1100 XOR 1010)?

    XOR gives 1 where the bits differ. 1100 and 1010 differ in the middle two positions, which gives 0110, or 6.
  2. 2. Which statement clears bit 4 of the unsigned variable x and leaves the other bits alone?

    ~(1u << 4) has every bit set except bit 4, so ANDing with it forces bit 4 to 0. XOR toggles instead of clearing, and the last option clears every other bit.
  3. 3. With unsigned char f = 0xF0;, why is ~f == 0x0F false?

    Integer promotion turns f into an int before ~ is applied. Cast back with (unsigned char)~f, or work in unsigned int.
  4. 4. Why is uint64_t big = 1 << 40; a bug?

    The type of the left operand decides the width of the shift; the type of the variable you store into does not matter. Write 1ULL << 40.
  5. 5. How does C parse if (flags & MASK == 0)?

    == has higher precedence than &, so the comparison happens first. GCC warns about it with -Wall; always parenthesize (flags & MASK).

Summary

  • Bits are powers of two; write them as hex, or as C23 binary literals like 0b0010'1101. Our server's C library doesn't support %b yet, so print bits with a small loop.
  • & (both), | (either), ^ (different) and ~ (flip) work bit by bit; << and >> move bits, like multiplying or dividing unsigned values by powers of two.
  • Masks built with 1u << n let you test (x & m), set (x |= m), clear (x &= ~m) and toggle (x ^= m) bits; "shift down, then mask" extracts fields.
  • Flags give each option one bit; test all of several flags with (x & m) == m.
  • Small types are promoted to int, so cast ~x back. Shift only unsigned values, by counts smaller than their width.
  • C23's <stdbit.h> standardizes bit counting; until your C library has it, use a portable loop or compiler built-ins with a note.
  • Bitwise operators bind more loosely than comparisons: write (x & mask) == 0.

Next: Operator Precedence, the Ternary and Comma Operators