Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 171 ยท Operators

Bitwise Operators

Learn the C++ bitwise operators & | ^ ~ << >>: masks, setting and clearing bits, shift rules, enum flags, std::bitset and C++20 <bit> functions like popcount.

Every integer in your program is stored as a row of bits, ones and zeros. Most of the time you don't care, but sometimes the bits themselves are the data. File permissions, keyboard modifier keys, network packet headers, color channels packed into one number, chess boards in game engines, hash functions: all of them work with individual bits, and C++ gives you direct, zero-cost access to them through the bitwise operators.

In this lesson you'll learn to read numbers in binary, use &, |, ^, ~, << and >>, and apply the four everyday bit operations: test, set, clear and toggle. You'll also see the shift rules that cause undefined behavior, how to build type-safe flags with enum class, and the modern helpers in std::bitset and the C++20 <bit> header.

Seeing the bits

To work with bits, you need to see them. std::format and std::println print an integer in binary with the b format type, and {:08b} pads it to eight digits with leading zeros. For writing values, use a binary literal with the 0b prefix; digit separators ' keep long ones readable.

Each bit position stands for a power of two. The rightmost bit (bit 0) 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
0b0010'1101:   0   0   1   0   1   1   0   1   = 32 + 8 + 4 + 1 = 45

Do bit manipulation on unsigned types, such as unsigned int, std::uint8_t or std::uint32_t from <cstdint>. Their bits mean exactly what they look like, shifts never touch a sign bit, and overflow is well defined. The examples here follow that rule.

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 bits differ
~a NOT (complement) the bit was 0 (every bit flips)
a << n left shift bits move n places left; zeros fill in on the right
a >> n right shift bits move n places right

The first three work bit by bit, comparing position 0 of a with position 0 of b, position 1 with position 1, and so on. Each also has a compound form: &=, |=, ^=, <<= and >>=.

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 std::cin or std::getline), it gets the next line from this box.

Notice the static_cast<std::uint8_t> around ~a and a << 1. The reason is explained a little further down, in "Watch out: promotion and the ~ operator".

Masks: test, set, clear and toggle

A mask is a value with ones exactly in the bit positions you care about. You build a mask for bit n with 1u << n, and then 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; ~ makes a mask of all ones except bit n
Toggle bit n x ^= 1u << n XOR with 1 flips the bit

Masks also work on groups of bits. x & 0xFF keeps the lowest 8 bits, which is how you pull the channels out of a packed color:

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 std::cin or std::getline), it gets the next line from this box.

The color example is the pattern behind most binary formats: shift the field down to bit 0, then mask off everything above it. Going the other way, shift each part into place and combine them with |.

Watch out: promotion and the ~ operator

Bitwise operators follow the same promotion rules as arithmetic (see Arithmetic Operators): operands smaller than int, such as std::uint8_t and char, are converted to int first. So ~a for an 8-bit a produces a 32-bit int in which all the upper bits are now ones, and as a signed int that's a negative number.

C++ Why ~ needs a cast on small types

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 std::cin or std::getline), it gets the next line from this box.

~flags == mask is false because the int on the left is -241 while the right side is 15. The example compiles with a warning on purpose: GCC spots this exact mistake (comparison of promoted bitwise complement of an unsigned value with unsigned). 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

x << n moves every bit n places to the left, which for unsigned values is the same as multiplying by 2โฟ (bits pushed off the top are lost). x >> n moves them right, the same as dividing by 2โฟ and rounding down. Compilers already turn x * 8 into a shift when it's faster, so write whichever expresses your intent.

Three rules keep shifts safe:

  1. The shift count must be less than the width of the (promoted) left operand. Shifting a 32-bit value by 32 or more, or by a negative amount, is undefined behavior. 1 << 40 is a bug because 1 is an int; write 1ULL << 40 or std::uint64_t{1} << 40.
  2. Right-shifting a negative number copies the sign bit (an arithmetic shift), so -16 >> 2 is -4. This was implementation-defined before C++20; C++20 requires two's complement and fixes this behavior.
  3. Left-shifting signed values that go past the top bit was undefined before C++20. C++20 defines it (the result wraps), but code that does it is still confusing. Use unsigned types.
C++
std::uint64_t big = 1ULL << 40;    // OK: 1099511627776
std::uint32_t bad = 1u << 32;      // undefined: count equals the width (GCC warns)
int negative = -16 >> 2;           // -4 (sign bit copied, guaranteed since C++20)

Flags with enums

A set of yes/no options fits neatly into one integer, one bit per option. That's how file permissions on Linux work: read is 4, write is 2, execute is 1, so chmod 750 means owner 7 (rwx), group 5 (r-x), others 0.

With a plain (unscoped) enum the values convert to integers automatically, so | and & just work. A scoped enum class is safer, because it doesn't silently mix with other integers, but you have to give it the operators yourself. Here is a compact, complete version using std::to_underlying from C++23 to get at the integer inside:

C++ Type-safe 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 std::cin or std::getline), it gets the next line from this box.

You'll learn more about operator functions in Operator Overloading and about scoped enums in Enumerations.

std::bitset and the <bit> header

You don't always have to juggle masks yourself. Two standard tools do the bookkeeping:

  • std::bitset<N> (in <bitset>) is a fixed-size row of N bits with readable member functions: set(i), reset(i), flip(i), test(i), count(), all(), any(), none() and to_string(). It also supports & | ^ ~ << >>. It gets its own lesson in std::bitset.
  • <bit> (C++20) offers fast functions on unsigned integers that map to single CPU instructions on most hardware:
Function Returns 0b0010'1100 (44)
std::popcount(x) number of 1 bits 3
std::has_single_bit(x) is x a power of two? false
std::bit_width(x) bits needed to store x 6
std::bit_ceil(x) / std::bit_floor(x) nearest power of two up / down 64 / 32
std::countl_zero(x) / std::countr_zero(x) leading / trailing zero bits 2 / 2 (for uint8_t)
std::rotl(x, n) / std::rotr(x, n) rotate: bits that fall off one end come back at the other

The <bit> functions only accept unsigned integer types, which stops you from asking questions like "how many bits are set in -1?" by accident.

C++ std::bitset and C++20 bit functions

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 std::cin or std::getline), it gets the next line from this box.

Note that std::bitset strings are written with bit 0 on the right, just like binary literals.

Classic bit tricks

You'll see these in performance-sensitive code and in interviews. All assume 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 has at most one bit set, which is how has_single_bit used to be written.
  • x & (~x + 1) isolates the lowest set bit.
  • a ^ a is always 0, and a ^ b ^ b is a again. That's the basis of simple checksums and the "find the number that appears once" puzzle.

The old XOR swap trick (a ^= b; b ^= a; a ^= b;) avoids a temporary variable, but it's slower than std::swap on modern CPUs, unreadable, and breaks if a and b are the same object. Don't use it.

Precedence pitfalls

The bitwise operators have lower precedence than comparisons, a decision inherited from C that everyone regrets. So this common 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 '&'). Also remember that & and | are not && and ||: they don't short-circuit, as you saw in Comparison and Logical Operators. And << and >> bind more loosely than +, so 1 << n + 1 means 1 << (n + 1). When bits are involved, use parentheses generously.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is 0b1100 ^ 0b1010?

    XOR gives 1 where the bits differ. 1100 and 1010 differ in the middle two positions, giving 0110 (6).
  2. 2. Which statement clears bit 4 of the unsigned variable x?

    ~(1u << 4) has every bit set except bit 4, so ANDing with it forces bit 4 to 0 and keeps the others. XOR would toggle the bit instead.
  3. 3. With std::uint8_t f = 0xF0;, why is ~f == 0x0F false?

    Small types are promoted to int before bitwise operations. Cast the result back with static_caststd::uint8_t(~f) to compare 8-bit values.
  4. 4. Why is std::uint64_t big = 1 << 40; a bug?

    The type of the left operand decides the width. Write 1ULL << 40 or std::uint64_t{1} << 40 so the shift happens in 64 bits.
  5. 5. How is if (flags & MASK == 0) parsed?

    == has higher precedence than &, so the comparison happens first. Always parenthesize bitwise expressions inside comparisons.

Summary

  • Print bits with {:08b}, write them with 0b literals and ' separators, and do bit work on unsigned types.
  • & (both), | (either), ^ (different) and ~ (flip) work bit by bit; << and >> move bits and act like multiplying or dividing 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.
  • Small types are promoted to int, so cast results like ~x back. Shifting by the type's width or more, or by a negative count, is undefined behavior.
  • Model sets of options as flags; with enum class, provide operator| and a test function using std::to_underlying.
  • std::bitset and the C++20 <bit> functions (popcount, has_single_bit, bit_width, rotl, โ€ฆ) do common bit tasks clearly and fast.
  • Bitwise operators bind more loosely than comparisons: parenthesize (x & mask) == 0.

Next: Operator Precedence and the Conditional Operator, the full table of who binds tighter, plus ?:, the comma operator and sizeof.