Build a mask with only bit n on, 1u << n, and combine it with a bitwise operator: set with x |= 1u << n;, clear with x &= ~(1u << n);, toggle with x ^= 1u << n;, and check with (x >> n) & 1u. Use an unsigned type, and a 64-bit one for bits 32 to 63: std::uint64_t{1} << n. A std::bitset does the same with set(n), reset(n), flip(n) and test(n).
Bits are numbered from 0, the least significant bit, which is the rightmost digit when you print a number in binary. Every operation on one bit is the same idea: make a mask that has only that bit on, then OR it in, AND it out or XOR it over. The sections below cover the four operators, setting a bit to a value you computed and working on several bits at once, the type traps that make 1 << n go wrong, std::bitset, named flags with enum class, and the C++20 <bit> functions, then a table to pick from. Each example runs on this page: hit Run, then edit the code and run it again.
1Bitwise operators with a maskRecommended
1u << n is an unsigned 1 shifted left n places: a mask with only bit n on. |= turns that bit on and leaves the others alone, &= with the inverted mask ~(1u << n) turns it off, and ^= flips it. To read a bit, shift it down to position 0 and mask it with & 1u, which gives exactly 0 or 1. The example prints the value with std::bitset<8> so you can watch each bit change.
#include <bitset> #include <cstdint> #include <iostream> // Print the low 8 bits so you can see which bit changed void show(const char* label, std::uint32_t x) { std::cout << label << std::bitset<8>(x) << '\n'; } int main() { std::uint32_t flags = 0b0000'0101; // bits 0 and 2 are set show("start: ", flags); // Set a bit: OR with a mask that has only that bit on flags |= 1u << 4; show("set 4: ", flags); // Clear a bit: AND with the inverted mask (every bit on except that one) flags &= ~(1u << 2); show("clear 2: ", flags); // Toggle a bit: XOR flips it, whatever it was flags ^= 1u << 0; show("toggle 0: ", flags); flags ^= 1u << 0; show("toggle 0: ", flags); // Check a bit: shift it down to position 0 and keep only that bit for (unsigned bit : {0u, 1u, 4u}) { unsigned value = (flags >> bit) & 1u; std::cout << "bit " << bit << " is " << value << '\n'; } // Or test against the mask; the result is the mask or 0, so compare to 0 bool on = (flags & (1u << 4)) != 0; std::cout << std::boolalpha << "bit 4 set: " << on << '\n'; std::cout << "as a number: " << flags << '\n'; }
Output
Starting from 00000101, setting bit 4 gives 00010101, clearing bit 2 gives 00010001, and toggling bit 0 twice goes to 00010000 and back to 00010001. The reads print bit 0 is 1, bit 1 is 0 and bit 4 is 1, and the final value is as a number: 17 (16 + 1). Note the second test: flags & (1u << 4) is 16, not 1, so compare it with 0 (or convert it to bool) instead of comparing it with 1. The parentheses around flags & (1u << 4) matter too; section 3 shows why.
2Set a bit to a value, and several bits at once
Often the new bit comes from a bool, and you want bit n to equal it whatever it was before. Clear the bit, then OR in the value shifted to the same place: (x & ~mask) | (std::uint32_t{value} << n). The well-known one-liner x ^= (-v ^ x) & mask, with v an unsigned 0 or 1, does the same with fewer operations, but the clear-then-OR form says what it does. The same two steps work for a mask with several bits on, and for a field of several bits, such as a 3-bit value packed into a register.
#include <bitset> #include <cstdint> #include <iostream> // Set bit n to value (true = 1, false = 0) without an if constexpr std::uint32_t with_bit(std::uint32_t x, unsigned n, bool value) { std::uint32_t mask = 1u << n; // Clear the bit, then OR in value shifted to the same place return (x & ~mask) | (std::uint32_t{value} << n); } // Read a field of `width` bits that starts at bit `pos` constexpr std::uint32_t get_field(std::uint32_t x, unsigned pos, unsigned width) { std::uint32_t mask = (1u << width) - 1; // width ones, e.g. 3 -> 0b111 return (x >> pos) & mask; } // Write a field: clear its bits, then OR in the new value (masked to fit) constexpr std::uint32_t set_field(std::uint32_t x, unsigned pos, unsigned width, std::uint32_t value) { std::uint32_t mask = ((1u << width) - 1) << pos; return (x & ~mask) | ((value << pos) & mask); } int main() { std::uint32_t x = 0b1010'1010; std::cout << std::bitset<8>(with_bit(x, 0, true)) << '\n'; std::cout << std::bitset<8>(with_bit(x, 1, false)) << '\n'; std::cout << std::bitset<8>(with_bit(x, 3, true)) << '\n'; // already 1: no change // Several bits at once: one mask, one operation std::uint32_t mask = (1u << 0) | (1u << 1) | (1u << 3); std::cout << "mask: " << std::bitset<8>(mask) << '\n'; std::cout << "set: " << std::bitset<8>(x | mask) << '\n'; std::cout << "clear: " << std::bitset<8>(x & ~mask) << '\n'; std::cout << "flip: " << std::bitset<8>(x ^ mask) << '\n'; std::cout << std::boolalpha; std::cout << "all set: " << ((x & mask) == mask) << '\n'; std::cout << "any set: " << ((x & mask) != 0) << '\n'; // A 3-bit field at bits 4..6, as in a packed register or file header std::cout << "field: " << get_field(x, 4, 3) << '\n'; std::uint32_t y = set_field(x, 4, 3, 5); std::cout << std::bitset<8>(y) << " field now " << get_field(y, 4, 3) << '\n'; }
Output
From 10101010, with_bit gives 10101011 (bit 0 set), 10101000 (bit 1 cleared) and 10101010 (bit 3 was already 1). With the mask 00001011 the three operators give 10101011, 10100000 and 10100001. Testing a several-bit mask needs a decision: (x & mask) == mask asks whether all of them are set and prints all set: false, while (x & mask) != 0 asks whether any is and prints any set: true. Bits 4 to 6 hold field: 2, and writing 5 into them gives 11011010 field now 5; masking the new value in set_field stops a value too big for the field from spilling into the neighbouring bits.
3Traps: the type of 1, ~ on small types, and precedence
Most bit bugs are type bugs. A plain 1 is a signed int, usually 32 bits, so 1 << 31 is a negative number and 1 << n for n of 32 or more is undefined behaviour: the compiler may return anything, and on x86 it often wraps the shift count, which looks like it works on some inputs. Integer promotion surprises people the other way: ~, << and the other operators turn a std::uint8_t or short into an int before they run. And &, | and ^ bind more loosely than ==.
#include <cstdint> #include <format> #include <iostream> int main() { unsigned n = 31; // 1. The literal 1 is a signed 32-bit int. 1 << 31 is negative, and // widening it to 64 bits copies the sign bit into the top 32 bits std::uint64_t wrong = 0; wrong |= 1 << n; std::uint64_t right = 0; right |= std::uint64_t{1} << n; // make the 1 as wide as the target std::cout << std::format("wrong: {:#018x}\n", wrong); std::cout << std::format("right: {:#018x}\n", right); // Bits 32..63 need a 64-bit 1 as well; 1 << 40 would be undefined n = 40; std::cout << std::format("bit 40: {:#x}\n", std::uint64_t{1} << n); // 2. ~ promotes a small type to int first, so the result has 32 bits std::uint8_t b = 0b1111'0000; std::cout << "~b as int: " << ~b << '\n'; std::cout << std::boolalpha << "~b == 0x0F: " << (~b == 0x0F) << '\n'; std::uint8_t inverted = ~b; // storing it back keeps the low 8 bits // Unary + prints a uint8_t as a number; << alone would print a char std::cout << "stored: " << +inverted << '\n'; // 3. == binds tighter than &, so this is flags & (mask == 0) unsigned flags = 0b0100; unsigned mask = 0b0010; std::cout << "flags & mask == 0: " << (flags & mask == 0) << '\n'; std::cout << "(flags & mask) == 0: " << ((flags & mask) == 0) << '\n'; }
Output
wrong |= 1 << n with n = 31 sets 33 bits, not one: wrong: 0xffffffff80000000, because the negative int is sign-extended to 64 bits. A 64-bit 1 gives right: 0x0000000080000000, and only a 64-bit 1 reaches bit 40: bit 40: 0x10000000000. The rule: make the 1 the same type as the value you change, with std::uint64_t{1}, 1ULL or decltype(x){1}. ~b on a std::uint8_t prints ~b as int: -241, so ~b == 0x0F is false; storing it back in a std::uint8_t gives the 15 you expected, which is why b &= ~mask still works. Last, flags & mask == 0 parses as flags & (mask == 0) and prints 0, the opposite of the right answer true: always parenthesise the &. Right shifts of negative numbers are arithmetic since C++20, but signed values still have these traps, so keep bit flags in unsigned types.
4std::bitset: named operations and a bounds check
std::bitset<N> is a fixed-size set of N bits with the operations spelled out: set(n), reset(n), flip(n) and test(n), plus set(n, value) for a computed bit. It also counts bits, prints itself in binary and converts to and from integers and strings, and its size can be larger than any integer type. Printing puts bit 0 on the right, the same order as a binary number.
#include <bitset> #include <iostream> #include <stdexcept> #include <string> int main() { std::bitset<8> bits("00000101"); // from a string of 0s and 1s bits.set(4); // set bit 4 to 1 bits.reset(2); // clear bit 2 bits.flip(0); // toggle bit 0 bits.set(7, true); // set to a given value std::cout << bits << '\n'; // operator[] reads and writes without a bounds check bits[1] = 1; std::cout << bits << " bit 1 = " << bits[1] << '\n'; // test() reads with a bounds check; count/any/none/all look at every bit std::cout << std::boolalpha; std::cout << "test(4): " << bits.test(4) << '\n'; std::cout << "count: " << bits.count() << " of " << bits.size() << '\n'; std::cout << "any: " << bits.any() << ", all: " << bits.all() << '\n'; // Convert to and from an integer and a string std::bitset<8> from_int(0x5A); std::cout << from_int.to_string() << " = " << from_int.to_ulong() << '\n'; std::cout << (bits & from_int) << " (AND works like on integers)\n"; // Out-of-range positions throw from set, reset, flip and test try { bits.test(8); } catch (const std::out_of_range& e) { std::cout << "out_of_range: " << e.what() << '\n'; } }
Output
After the four calls the set prints 10010000: bit 4 and bit 7 set, bit 2 cleared, and bit 0 toggled off. Writing bits[1] = 1 gives 10010010 bit 1 = 1. The whole-set queries print count: 3 of 8 and any: true, all: false, and 0x5A round-trips as 01011010 = 90. The difference from operator[] is the check: test(8) on an 8-bit set throws, and the program prints out_of_range: bitset::test: __position (which is 8) >= _Nb (which is 8) (the message text comes from GCC's library), while bits[8] would be undefined behaviour. The size is fixed when you compile; for a number of bits known only at run time use std::vector<bool> or an array of std::uint64_t words.
5Named flags with enum class
When each bit means something, such as read, write and execute permissions, give the bits names. An enum class with one bit per enumerator keeps the names scoped and stops a flag from mixing silently with an unrelated int, but it has no bitwise operators, so you define |, &, ^, ~ and the assignment forms once, through std::underlying_type_t. After that, set, clear and toggle read the same as on integers.
#include <cstdint> #include <iostream> #include <type_traits> // Each enumerator is one bit; enum class keeps the names scoped and typed enum class Perm : std::uint8_t { None = 0, Read = 1 << 0, Write = 1 << 1, Exec = 1 << 2, }; // enum class has no bitwise operators, so define the ones you need constexpr Perm operator|(Perm a, Perm b) { using U = std::underlying_type_t<Perm>; return static_cast<Perm>(static_cast<U>(a) | static_cast<U>(b)); } constexpr Perm operator&(Perm a, Perm b) { using U = std::underlying_type_t<Perm>; return static_cast<Perm>(static_cast<U>(a) & static_cast<U>(b)); } constexpr Perm operator^(Perm a, Perm b) { using U = std::underlying_type_t<Perm>; return static_cast<Perm>(static_cast<U>(a) ^ static_cast<U>(b)); } constexpr Perm operator~(Perm a) { using U = std::underlying_type_t<Perm>; return static_cast<Perm>(static_cast<U>(~static_cast<U>(a))); } constexpr Perm& operator|=(Perm& a, Perm b) { return a = a | b; } constexpr Perm& operator&=(Perm& a, Perm b) { return a = a & b; } constexpr Perm& operator^=(Perm& a, Perm b) { return a = a ^ b; } constexpr bool has(Perm set, Perm flag) { return (set & flag) == flag; } void show(Perm p) { std::cout << (has(p, Perm::Read) ? 'r' : '-') << (has(p, Perm::Write) ? 'w' : '-') << (has(p, Perm::Exec) ? 'x' : '-') << '\n'; } int main() { Perm p = Perm::Read | Perm::Write; show(p); p |= Perm::Exec; // set show(p); p &= ~Perm::Write; // clear show(p); p ^= Perm::Read; // toggle show(p); std::cout << std::boolalpha << "can exec: " << has(p, Perm::Exec) << '\n'; }
Output
The permissions go rw-, rwx after setting Exec, r-x after clearing Write, and --x after toggling Read, and the final check prints can exec: true. A plain enum or a set of constexpr unsigned constants needs no operators, because they convert to integers on their own; the price is that any integer is accepted where a flag is expected. To print flag names instead of letters, see converting an enum to a string.
6Counting and finding bits with <bit> (C++20)
The next questions after setting bits are usually "how many are set?" and "which is the lowest?". C++20's <bit> header answers them with std::popcount, std::countr_zero, std::countl_zero, std::bit_width, std::has_single_bit (is it a power of two?) and the rotations std::rotl and std::rotr, which compile to single CPU instructions where the CPU has them. They accept unsigned types only, so a signed argument is a compile error rather than a surprise. Two older tricks complete the set: x & -x keeps only the lowest set bit and x & (x - 1) clears it.
#include <bit> #include <cstdint> #include <format> #include <iostream> int main() { std::uint8_t x = 0b0110'1000; std::cout << std::format("x: {:08b}\n", x); // <bit> (C++20) works on unsigned integer types only. // popcount = how many bits are set std::cout << "popcount: " << std::popcount(x) << '\n'; // Trailing zeros = the index of the lowest set bit std::cout << "countr_zero: " << std::countr_zero(x) << '\n'; std::cout << "countl_zero: " << std::countl_zero(x) << '\n'; // Bits needed to hold x = the index of the highest set bit + 1 std::cout << "bit_width: " << std::bit_width(x) << '\n'; // Exactly one bit set, i.e. a power of two std::cout << std::boolalpha; std::cout << "has_single_bit: " << std::has_single_bit(x) << '\n'; std::cout << std::format("rotl(x, 3): {:08b}\n", std::rotl(x, 3)); // Classic tricks on the lowest set bit std::uint8_t lowest = x & -x; // isolate it std::uint8_t without = x & (x - 1); // clear it std::cout << std::format("lowest: {:08b}\n", lowest); std::cout << std::format("cleared: {:08b}\n", without); // Visit every set bit: take the lowest, clear it, repeat std::cout << "set bits:"; for (std::uint8_t rest = x; rest != 0; rest &= rest - 1) { std::cout << ' ' << std::countr_zero(rest); } std::cout << '\n'; }
Output
01101000 has popcount: 3 set bits, the lowest at index countr_zero: 3, one zero above the highest (countl_zero: 1 in 8 bits) and bit_width: 7. It is not a power of two, so has_single_bit: false, and rotating left by 3 wraps the top bits round: 01000011. The lowest set bit isolated is 00001000 and cleared is 01100000. The loop repeats the clear to visit each set bit and prints set bits: 3 5 6, which is the usual way to walk the members of a bit set. Before C++20, GCC and Clang offer __builtin_popcount and __builtin_ctz, and std::bitset<N>::count() works in any standard.
7Which should you use?
| Method | Safety | Standard | Best for |
|---|---|---|---|
| x |= 1u << n, &= ~, ^= | No | Any | Integers, registers, packed formats |
| (x & ~mask) | (v << n) | No | Any | Setting a bit or field to a computed value |
| std::bitset<N> | With test(), set(), reset() | Any | Fixed sets of flags, printing in binary |
| enum class + operators | Typed flags | C++11 | Named options in an API |
| std::popcount, countr_zero … | Unsigned only | C++20 | Counting, finding and rotating bits |
Frequently asked questions
How do I check if a bit is set in C++?
Shift it down and mask it: (x >> n) & 1u is 1 when bit n is set and 0 when it is not. The other common form, (x & (1u << n)) != 0, gives a bool; compare it with 0, never with 1, because x & (1u << n) is the mask value itself (16 for bit 4), and keep the parentheses, because == binds tighter than &. With a std::bitset, call bits.test(n).
Why does 1 << 32 not set bit 32?
1 is a 32-bit int, and shifting a value by its width or more is undefined behaviour, so 1 << 32 and 1 << 40 can produce anything; x86 hardware often wraps the count, so it may look like bit 0 or bit 8. Make the 1 as wide as the target: std::uint64_t{1} << n or 1ULL << n. Even 1 << 31 is a trap: it is a negative int, and OR-ing it into a 64-bit value sets the top 33 bits.
How do I count the set bits in an integer in C++?
In C++20 use std::popcount(x) from <bit>; it takes unsigned types only. In any standard, std::bitset<64>(x).count() gives the same number. GCC and Clang also have __builtin_popcount (and __builtin_popcountll for 64 bits), which is what older code uses.
Is std::bitset slower than the bitwise operators?
For a fixed size it does the same |, &, ^ and shifts on whole machine words, so with optimisation on, operator[] and the operators typically compile to the same instructions as hand-written masks. test, set, reset and flip with an index add a bounds check that throws std::out_of_range. The real limits are elsewhere: the size is fixed at compile time and to_ulong() throws when the set does not fit in an unsigned long.
Should I use bit-fields to store flags in C++?
Bit-fields such as struct Status { unsigned ready : 1; unsigned error : 1; }; let you write s.ready = 1 instead of masks, and they are fine for flags that stay inside one program. Avoid them for anything with a fixed layout, such as file formats, network packets or hardware registers: the order and packing of bit-fields is up to the compiler. You also cannot take the address of a bit-field or set several of them in one operation, which masks can.
How do I set bit n in an array of bits larger than 64?
Split n into a word index and a bit index: with std::vector<std::uint64_t> words, set it with words[n / 64] |= std::uint64_t{1} << (n % 64), and clear, toggle and check the same way. If the size is known when you compile, std::bitset<N> does this for you; if it is not, std::vector<bool> stores one bit per element and v[n] = true sets it.