Module 1 · Basics
1.3Operators and bit operations
Operators do arithmetic, compare values and combine conditions. Bit operators work on the single bits inside an integer, so you can pack flags or DNA bases into a few bits. Learn both, and the pitfalls the compiler and the sanitizers catch for you.
On this page
- Key terms
- In 30 seconds
- Arithmetic and assignment
- Comparisons and logic
- && and || stop early
- Choosing a value with ? :
- Seeing the bits
- The bitwise operators
- Shifting bits
- Flags and masks
- Packing DNA into two bits
- Which one should I use?
- Under the hood
- Common pitfalls
- ~ on a small type gives a negative int
- x & mask == 0 tests the wrong thing
- Shifting by the width or more
- Try it yourself
Key terms
- operator
- A symbol like
+,<or&&that computes a value from one or two values, its operands. - compound assignment (
+=) x += 5is short forx = x + 5. Every arithmetic and bit operator has one:-=,*=,|=,<<=and so on.- increment (
++) and decrement (--) - Add 1 to a variable, or subtract 1.
++xgives the new value;x++gives the old one. - short-circuit evaluation
&&and||stop as soon as the answer is known, so the right side may never run.- ternary operator (
c ? a : b) - Gives
aif the conditioncis true andbif it's false. - bit
- One binary digit, 0 or 1. A
std::uint8_tholds 8 of them. - bitwise operator
&(AND),|(OR),^(XOR) and~(NOT): they work on each bit position separately.- shift (
<<,>>) - Moves every bit of an integer left or right by a number of places.
- flag
- One bit that stands for a yes/no setting, like read permission.
- mask
- An integer whose 1 bits pick out the bits you care about, used with
&,|or^. - precedence
- Which operator is applied first when an expression has several, like
*before+. - integer promotion
- Before arithmetic, values of types smaller than
int(likestd::uint8_torbool) are converted toint.
Programs spend most of their time computing small things: adding a score, checking a threshold, deciding between two values. Operators do that work. C++ also lets you reach inside an integer and work on its single bits, which is how fast code packs eight yes/no settings into one byte, or four DNA bases into the space of one character.
In 30 seconds
+,-,*,/and%do arithmetic;+=and friends update a variable in place;++and--add or subtract 1.- Comparisons (
==,<, …) give abool.&&,||and!combine them, and&&and||stop as soon as the answer is known. &,|,^and~work on each bit;<<and>>move bits. Together they set, clear, test and pack bits.- Shifting by the type’s width or more is undefined behavior, and
x & mask == 0doesn’t mean what it looks like. Both are caught for you.
Arithmetic and assignment
The arithmetic operators are +, -, *, / and % (the remainder); Integers and floating-point numbers covers how / and % behave on integers. To change a variable by some amount, use a compound assignment: x += 5 means x = x + 5.
++ adds 1 and -- subtracts 1. Written before the variable (++reads), the expression gives the new value. Written after (reads++), it gives the old value, then changes the variable.
#include <print>
int reads = 10;
reads += 5; // 15
reads *= 2; // 30
++reads; // 31
std::println("{}", reads);
int before = reads++;
std::println("{} {}", before, reads);
--reads;
std::println("{}", reads);Output
31 31 32 31
When you only want to change the variable, as in ++reads; on its own line, both forms do the same thing. Use ++x: it says exactly that.
Comparisons and logic
The comparison operators are == (equal), != (not equal), <, <=, > and >=. Each gives a bool. Note the double =: a single = assigns.
Three logical operators combine bool values: && (and) is true when both sides are, || (or) when at least one side is, and ! (not) flips true and false.
#include <print>
int quality = 32;
bool high = quality >= 30;
bool low = quality < 20;
std::println("{} {} {}", high, low, !high);
std::println("{}", high && !low);
std::println("{}", quality == 30 || quality == 32);
std::println("{}", quality != 32);Output
true false false true true false
&& and || stop early
&& checks its left side first. If that’s false, the whole thing is false, so the right side never runs. || stops when its left side is true. This is called short-circuit evaluation. The program below shows it with a function that prints when it’s called:
#include <print>
bool check(int id, bool result) {
std::println("checking {}", id);
return result;
}
int main() {
bool both = check(1, false) && check(2, true);
std::println("both: {}", both);
bool either = check(3, true) || check(4, false);
std::println("either: {}", either);
}Output
checking 1 both: false checking 3 either: true
Checks 2 and 4 never ran. You can rely on this to guard a check that would otherwise be wrong. Dividing an integer by zero is undefined behavior, but here the division only happens when count isn’t zero:
#include <print>
int total = 90;
int count = 0;
bool high_average = count != 0 && total / count > 10;
std::println("{}", high_average);Output
false
Choosing a value with ? :
The ternary operator condition ? a : b gives a if the condition is true and b otherwise. It’s handy when a value depends on one condition:
#include <print>
int quality = 12;
int a = 4;
int b = 9;
std::println("{}", quality >= 20 ? "pass" : "fail");
int larger = a > b ? a : b;
std::println("{}", larger);Output
fail 9
Seeing the bits
Every integer is stored as bits, binary digits that are 0 or 1. Each bit position is worth twice the one to its right, so the 8 bits of a byte are worth 128, 64, 32, 16, 8, 4, 2 and 1. To see them, print with the format {:08b}: b means binary, 8 is the width, and the 0 pads with zeros.
#include <cstdint>
#include <print>
std::uint8_t level = 13;
std::println("{:08b}", level);
std::println("{}", 0b1010'0001);Output
00001101 161
std::uint8_t (from <cstdint>) is an unsigned integer of exactly 8 bits, a good type for playing with one byte. 0b starts a binary literal, and ' is only a separator for your eyes.
| Bit position | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 |
|---|---|---|---|---|---|---|---|---|
| Worth | 128 | 64 | 32 | 16 | 8 | 4 | 2 | 1 |
13 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 1 |
13 is 8 + 4 + 1. Bit 0, on the right, is called the lowest bit.
The bitwise operators
The bitwise operators line up two integers and work on each bit position on its own:
| Operator | Name | A result bit is 1 when |
|---|---|---|
a & b | AND | both bits are 1 |
a | b | OR | at least one bit is 1 |
a ^ b | XOR | the two bits are different |
~a | NOT | the bit was 0 (every bit flips) |
#include <cstdint>
#include <print>
std::uint8_t a = 0b1100'1010;
std::uint8_t b = 0b1010'0110;
std::println("a {:08b}", a);
std::println("b {:08b}", b);
std::println("a & b {:08b}", a & b);
std::println("a | b {:08b}", a | b);
std::println("a ^ b {:08b}", a ^ b);
std::println("~a {:08b}", static_cast<std::uint8_t>(~a));Output
a 11001010 b 10100110 a & b 10000010 a | b 11101110 a ^ b 01101100 ~a 00110101
Read each column from top to bottom to check the rules. The static_cast on the last line is needed because of integer promotion; Common pitfalls shows what happens without it.
Shifting bits
x << n moves every bit of x left by n places and fills the right with zeros. x >> n moves them right, and the lowest bits fall off. For unsigned numbers, each step left doubles the value and each step right halves it, dropping any remainder.
#include <print>
unsigned int bits = 0b0000'0110;
std::println("{:08b} {}", bits, bits);
std::println("{:08b} {}", bits << 2, bits << 2);
std::println("{:08b} {}", bits >> 1, bits >> 1);
std::println("{:08b}", 1u << 7);Output
00000110 6 00011000 24 00000011 3 10000000
1u << n is the usual way to write “a number with only bit n set”. The u makes the 1 unsigned.
Flags and masks
A flag is one bit that stands for a yes/no setting. Give each flag its own bit, and one small integer holds all of them. A mask is a value whose 1 bits pick out the bits you want to work on. Four patterns cover almost everything:
- Set bits:
flags |= mask - Clear bits:
flags &= ~mask - Flip bits:
flags ^= mask - Test bits:
(flags & mask) != 0
#include <cstdint>
#include <print>
constexpr std::uint8_t perm_read = 0b001;
constexpr std::uint8_t perm_write = 0b010;
constexpr std::uint8_t perm_run = 0b100;
std::uint8_t perms = perm_read | perm_write;
std::println("{:03b}", perms);
perms |= perm_run; // set: 111
perms &= ~perm_write; // clear: 101
perms ^= perm_read; // flip: 100
std::println("{:03b}", perms);
std::println("can write: {}", (perms & perm_write) != 0);
std::println("can run: {}", (perms & perm_run) != 0);Output
011 100 can write: false can run: true
Key ideaLogical or bitwise?
&&, || and ! work on whole true/false values. &, |, ^ and ~ work on each bit of an integer. They look alike but aren’t interchangeable.
With a = 1 and b = 2, a && b is true because both are nonzero, but a & b is 0, because 1 (01) and 2 (10) share no bits:
#include <print>
int a = 1;
int b = 2;
std::println("{} {}", a && b, a & b);Output
true 0
Packing DNA into two bits
DNA has four bases, A, C, G and T. Four choices fit in 2 bits, so give each base a code: A = 00, C = 01, G = 10, T = 11. One byte then holds four bases instead of one character. To add a base, shift what you have left by 2 to make room, then | the new code into the free bits. To read a base back, shift it down to the bottom and mask it with 0b11.
#include <cstdint>
#include <print>
// A = 00, C = 01, G = 10, T = 11
std::uint8_t packed = 0;
packed = (packed << 2) | 0b10; // G
packed = (packed << 2) | 0b00; // A
packed = (packed << 2) | 0b11; // T
packed = (packed << 2) | 0b01; // C
std::println("GATC packed: {:08b}", packed);
unsigned int third = (packed >> 2) & 0b11;
std::println("third base: {:02b}", third);Output
GATC packed: 10001101 third base: 11
The third base is 11, which is T. A human genome has about 3 billion bases, so storing it at 2 bits per base instead of 8 saves three quarters of the memory. Module 12, C++ for bioinformatics, builds a full packed sequence type on this idea.
Which one should I use?
| What | When | Why | How |
|---|---|---|---|
Logical operators (&&, ||, !) | Combining conditions that are true or false. | They short-circuit, so a guard on the left protects the check on the right. | count != 0 && total / count > 10 |
Bitwise operators (&, |, ^, ~) | Setting, clearing, flipping or testing bits in an integer: flags, masks, packed data. | They work on every bit position at once, in one instruction. | perms |= perm_run |
Shifts (<<, >>) | Moving bits into place, or building a mask for bit n. | Packing and unpacking needs bits at exact positions. | 1u << n, (packed >> 2) & 0b11 |
Ternary (? :) | Picking one of two values based on one condition. | It’s an expression, so it can initialize a variable or go inside a call. | int larger = a > b ? a : b; |
Rule of thumb: logical operators for conditions, bitwise operators for bits, unsigned types for anything you shift, and parentheses whenever you mix bit operators with comparisons.
Under the hood
Arithmetic never happens on types smaller than int. Before a & b is computed, two std::uint8_t values are converted to int: this is integer promotion. The result of a bit operation on two bytes is an int, 4 bytes on this platform:
#include <cstdint>
#include <print>
std::uint8_t a = 0b1100'1010;
std::uint8_t b = 0b1010'0110;
std::println("{} {}", sizeof(a), sizeof(a & b));Output
1 4
That’s usually harmless, because the value fits. It matters for ~, which flips all 32 bits of the int, including the 24 new zero bits on the left (see the first pitfall below).
Each bit operator and shift is a single CPU instruction, as cheap as an addition. You don’t need shifts to make code fast, though: the compiler already turns x * 8 on an unsigned number into x << 3. Write * when you mean a product, and shifts when you mean bit positions.
Modern C++Negative numbers have a fixed bit pattern
Since C++20, signed integers are guaranteed to use two’s complement: -1 is all 1 bits, and the highest bit is the sign. Still, keep bit operations on unsigned types such as std::uint8_t and std::uint32_t. Their bits mean exactly what you see.
Common pitfalls
~ on a small type gives a negative int
Because of integer promotion, ~mask on a std::uint8_t is an int with all 32 bits flipped, and its top bit (the sign) is now 1. Printed as binary, it’s a negative number:
#include <cstdint>
#include <print>
std::uint8_t mask = 0b0000'1111;
std::println("{:08b}", ~mask);
std::println("{:08b}", static_cast<std::uint8_t>(~mask));Output
-0010000 11110000
The fix is on the second line: static_cast the result back to the small type, which keeps only its 8 bits. Assigning works too, as in perms &= ~perm_write; above.
x & mask == 0 tests the wrong thing
== has higher precedence than &, so flags & mask == 0 means flags & (mask == 0). GCC and Clang both warn about it, and with warnings as errors it doesn’t compile:
#include <cstdint>
#include <print>
std::uint8_t flags = 0b0110;
std::uint8_t mask = 0b0100;
if (flags & mask == 0) {
std::println("bit is off");
}The compiler rejects this
main.cpp: In function ‘int main()’:
main.cpp:6:18: error: suggest parentheses around comparison in operand of ‘&’ [-Werror=parentheses]
6 | if (flags & mask == 0) {
| ~~~~~^~~~
cc1plus: all warnings being treated as errorsThe fix is to add parentheses: if ((flags & mask) == 0). Put parentheses around every bit operation inside a comparison; nobody remembers the whole precedence table.
Shifting by the width or more
An unsigned int has 32 bits on this platform. Shifting it by 32 or more places is undefined behavior: the result isn’t 0, it isn’t anything you can rely on. The compiler can’t see it when the shift amount is a variable; UndefinedBehaviorSanitizer catches it when the program runs:
#include <print>
unsigned int one = 1;
int position = 32;
unsigned int bit = one << position;
std::println("{}", bit);This fails when it runs
main.cpp:5:24: runtime error: shift exponent 32 is too large for 32-bit type 'unsigned int'
Undefined behaviorCheck the shift amount
Shifting a 32-bit value by 32 doesn’t reliably give 0: the result can change between compilers, CPUs and optimization levels. Check that position < 32 first, or use a wider type like std::uint64_t when you need more bits. Shifting a signed number is easy to misread (a negative number shifted right stays negative), so shift unsigned types.
Try it yourself
Try it yourself
Sequencing tools store facts about each read as flags in one integer: bit 0 means “paired”, bit 2 means “unmapped” and bit 4 means “reverse strand”. This read has the flags 0b1'0001. Print whether it’s on the reverse strand and whether it’s unmapped. Then mark it as unmapped, clear the paired flag, and print the flags as 5 binary digits.
#include <cstdint>
#include <print>
int main() {
constexpr std::uint16_t paired = 1u << 0;
constexpr std::uint16_t unmapped = 1u << 2;
constexpr std::uint16_t reverse = 1u << 4;
std::uint16_t flags = 0b1'0001;
std::println("{:05b}", flags);
}Expected output
reverse: true unmapped: false 10100
Show a hint
Test a flag with (flags & mask) != 0, set one with |=, and clear one with &= ~mask. Put parentheses around each & before comparing.
Show a solution
#include <cstdint>
#include <print>
int main() {
constexpr std::uint16_t paired = 1u << 0;
constexpr std::uint16_t unmapped = 1u << 2;
constexpr std::uint16_t reverse = 1u << 4;
std::uint16_t flags = 0b1'0001;
std::println("reverse: {}", (flags & reverse) != 0);
std::println("unmapped: {}", (flags & unmapped) != 0);
flags |= unmapped;
flags &= ~paired;
std::println("{:05b}", flags);
}flags is 0b1'0001, so bit 0 (paired) and bit 4 (reverse) are on, and bit 2 (unmapped) is off. flags |= unmapped turns bit 2 on, and flags &= ~paired turns bit 0 off, leaving 1'0100.
Saved in this browser only.