Loading lessons...
Bitwise Operators and Bit Flags
C++ Bitwise Operators
Numbers live inside the computer as bits: 0 and 1. Bitwise operators work directly on those bits - great for fast flags and hardware.
Binary look at a number
Use std::bitset from <bitset> to show the bit pattern:
#include <bitset>
cout << bitset<8>(5) << endl; // 00000101
Here 5 is 00000101 in binary.
The six bitwise operators
&AND: 1 only when both bits are 1.|OR: 1 when at least one bit is 1.^XOR: 1 when the bits differ.~NOT: flips every bit.<<shift left: move the bits left.>>shift right: move the bits right.
A small program
#include <iostream>
#include <bitset>
using namespace std;
int main() {
cout << bitset<4>(6 & 3) << endl; // 0010
cout << bitset<4>(6 | 3) << endl; // 0111
cout << bitset<4>(6 ^ 3) << endl; // 0101
cout << (1 << 3) << endl; // 8
return 0;
}
Shifts: quick multiplication and division
Moving bits left by one doubles the number; moving right by one halves it. 1 << 3 moves the 1-bit three spots, giving 8.
Bit flags: many booleans in one int
A common trick is to pack several true/false settings into a single integer, one bit each. Each bit is a flag.
int flags = 0; // everything off
flags = flags | 1; // turn on bit 0
flags = flags | (1 << 2); // turn on bit 2
bool on = (flags & (1 << 2)) != 0; // is bit 2 on?
Bit flags save memory (one value instead of many booleans) and are used a lot in systems programming.
TL;DR
- Bitwise ops work per bit:
&,|,^,<<,<<,~. std::bitset<8>prints the bits of a number.<<shifts left,>>shifts right.- Store many true/false flags in one int with the bit-flag pattern.