Bitwise NOT ~ (Complement)
What you'll learn: How to use the ~ operator to flip every individual bit in a variable from 0 to 1 and vice versa.
The Light Switch Array
Imagine a long hallway with eight light switches in a row. Some are up (1), and some are down (0). The Bitwise NOT operator, represented by the tilde symbol ~, is like a "master flip" command. When you apply it, every single switch instantly swaps its position. If it was ON, it becomes OFF. If it was OFF, it becomes ON.
In C, this is a unary operator, meaning it only acts on one piece of data at a time. It doesn't compare two numbers; it simply looks at the binary representation of a single number and inverts it.
Seeing the Flip
Computers store integers as a series of bits. When you use ~, the computer looks at the binary pattern and performs a "Logical Negation" on every bit.
~0becomes1~1becomes0
If we look at an 8-bit unsigned integer (a char in C), the transformation looks like this:
unsigned char myByte = 5; // Binary: 00000101
unsigned char result = ~myByte; // Binary: 11111010 (Decimal: 250)
In the example above, the zeros at the front—which we usually ignore in math—suddenly become active ones. This is why bitwise operations feel different than standard arithmetic; they treat the number like a collection of individual toggles rather than a single value.
The Negative Surprise
One quirk you will notice when using ~ with signed integers (the standard int) is that the result often looks like a completely different negative number. For instance, ~5 might result in -6.
This happens because most modern computers use a system called "Two's Complement" to handle negative numbers. In this system, the very first bit determines if a number is positive or negative. When you use ~, you are flipping that "sign bit" along with all the others. While the math behind it is specific, the behavior of the operator remains consistent: it is a pure, total inversion of every bit in the container.
Key takeaway
The ~ operator flips every bit in a value, turning all 0s into 1s and all 1s into 0s.