The short answer
The bitwise NOT operator, ~, flips every bit of its operand. Each 0 becomes 1, and each 1 becomes 0. It takes only one operand, so it is a unary operator. The ~ operator is one of the unary operators in c, and the others include ! and the unary minus.
An example with unsigned values
#include <iostream>
int main() {
unsigned int x = 5; // ...0101 in binary
std::cout << "x = " << x << '\n';
std::cout << "~x = " << ~x << '\n';
return 0;
}
Output, on a system where unsigned int is 32 bits:
x = 5
~x = 4294967290
For any unsigned type, ~x equals the largest value of that type minus x. With a 32-bit unsigned int, that is 4294967295 minus 5, which is 4294967290.
The ~ operator does not change x. It produces a new value, so write x = ~x; if you want to keep the result.
Signed values
For signed integers, the result depends on how the type is stored. C++20 requires two’s complement, the format used by essentially all current systems. In two’s complement, ~x equals -x - 1, so ~5 is -6.
int y = 5;
std::cout << "~y = " << ~y << '\n'; // prints -6
Before C++20, the storage format of signed integers was left to the implementation, although two’s complement was the usual choice.
Watch the type
Operators like ~ work on int at minimum. A small type such as unsigned char is promoted to int first, so the result is an int, not an unsigned char.
unsigned char c = 0x0F; // 00001111
int wide = ~c; // -16, with every bit above the low four set
unsigned char narrow = ~c; // 0xF0 (11110000) after conversion
Clearing bits with ~
Combining ~ with & clears bits. The expression x &= ~mask clears every bit that is set in mask and leaves the others alone.
unsigned int flags = 0b1111;
unsigned int bit_two = 0b0100;
flags &= ~bit_two; // clears bit 2, so flags is 0b1011
Not the same as !
! is logical NOT, and it works on true and false values. ~ works on each bit. They give different answers for the same value:
!5isfalse, which prints as 0, because 5 is nonzero.~5is-6for a signedint.
Mixing them up is a common source of bugs, so check which operator you mean.
Summary
~ flips each bit of a value and gives back a new value. For unsigned types, the result is the maximum value minus the original. For signed types, expect a negative number, such as -6 for ~5. Use ~ with & to clear bits, and remember that ! is a different operator.