0
0
Cprogramming~5 mins

Bitwise NOT in C

Choose your learning style9 modes available
Introduction
Bitwise NOT flips every bit in a number from 0 to 1 or from 1 to 0. It helps us quickly invert bits for tasks like toggling flags or creating masks.
You want to invert all bits of a number to get its complement.
You need to toggle bits in a binary flag to switch states.
You want to create a mask that excludes certain bits.
You are working with low-level hardware or embedded systems where bit manipulation is common.
Syntax
C
int bitwise_not = ~number;
The ~ operator flips every bit of the integer 'number'.
The result depends on the size of the integer and uses two's complement representation.
Examples
Flips the lower 4 bits from 1 to 0 and upper bits from 0 to 1.
C
int number = 0b00001111;
int result = ~number;  // result flips bits of 00001111
All bits of zero become 1, resulting in -1 in two's complement.
C
int number = 0;
int result = ~number;  // flips all bits of 0
All bits of -1 are 1, flipping them results in 0.
C
int number = -1;
int result = ~number;  // flips all bits of -1
Sample Program
This program shows how bitwise NOT flips all bits of the number 15. The output shows the original and inverted values.
C
#include <stdio.h>

int main() {
    int original_number = 15;  // binary: 00000000 00000000 00000000 00001111
    int inverted_number = ~original_number;

    printf("Original number: %d\n", original_number);
    printf("Inverted number (bitwise NOT): %d\n", inverted_number);

    return 0;
}
OutputSuccess
Important Notes
Time complexity is O(1) because bitwise NOT operates on fixed-size integers directly.
Space complexity is O(1) as no extra memory is needed beyond variables.
Common mistake: forgetting that bitwise NOT results depend on integer size and signed representation, so the result may be negative.
Use bitwise NOT when you need to invert bits quickly; for arithmetic negation, use the unary minus operator (-).
Summary
Bitwise NOT (~) flips every bit of an integer.
It is useful for toggling bits and creating bit masks.
The result depends on the integer size and two's complement representation.