~ - bitwise NOT (unary complement)
suggest change// :glot
#include <iostream>
int main() {
const unsigned char a = 234; // 1110 1010b (0xEA)
const unsigned char b = static_cast<unsigned char>(~a); // 0001 0101b
std::cout << "a = " << static_cast<int>(a) <<
", b = " << static_cast<int>(b) << '\n';
}
a = 234, b = 21
Why
A bitwise NOT (unary complement) operates on the bit level and flips each bit. If it is a 1, it becomes a 0, and if it is a 0, it becomes a 1. The operand is integer-promoted first, so ~ of an unsigned char is an int with every promoted bit flipped. Storing that result back in an unsigned char keeps the low CHAR_BIT bits. On those bits, ~a matches a XOR’d with an all-ones value of that width:
unsigned char a = 234; // 1110 1010b (0xEA)
unsigned char b = ~a; // 0001 0101b (0x15)
unsigned char c = a ^ ~0;
The bitwise NOT can also produce the maximum value of an unsigned type. The output below assumes a 32-bit unsigned int:
// :glot
#include <iostream>
int main() {
const unsigned int i = ~0u;
const unsigned char c = static_cast<unsigned char>(~0u);
std::cout << "max uint = " << i << '\n'
<< "max uchar = " << static_cast<unsigned int>(c) << '\n';
}
max uint = 4294967295
max uchar = 255
The bitwise NOT does not change the original object, and there is no compound assignment operator, so a ~= 10 is ill-formed.
Do not confuse bitwise NOT (~) with logical NOT (!). Bitwise NOT flips each bit; logical NOT tests the whole value. In particular, (!1) != (~1).