C program to flip all bits of a binary number

Write a C program to input a number from user and flip all bits of the given number (in binary representation) using bitwise operator. How to flip all bits of a binary number using bitwise operator in C programming.



Input any number: 22


Number after bits are flipped: -23 (in decimal)

Required knowledge

Bitwise operators, Data types, Variables and Expressions, Basic input/output

Logic to flip all bits of a number

Flipping a bit means toggling or inverting the current bit status. If the current bit is set i.e. 1 than invert it to 0 and vice versa.

To flip all bits of a binary number you can run loop from 0 to size of the integer and flip individual bit at a time. However, C language has given bitwise complement ~ operator for the purpose.

Bitwise complement ~ evaluates complement of the operand bit. It evaluate to 1 if corresponding bit of the operand is 0 otherwise evaluate to 0.

Therefore to flip all bits of a number say num, you can use ~num.

Program to flip all bits of a number

 * C program to count flip all bits of a binary number using bitwise operator

#include <stdio.h>

int main()
    int num, flippedNumber;

    /* Input number from user */
    printf("Enter any number: ");
    scanf("%d", &num);

    flippedNumber = ~num;

    printf("Original number = %d (in decimal)\n", num);
    printf("Number after bits are flipped = %d (in decimal)", flippedNumber);

    return 0;


Enter any number: 22
Original number = 22 (in decimal)
Number after bits are flipped = -23 (in decimal)

Happy coding 😉

About Pankaj

Pankaj Prakash is the founder, editor and blogger at Codeforwin. He loves to learn new techs and write programming articles especially for beginners. He works at Vasudhaika Software Sols as a Software Design Engineer and manages Codeforwin. In short Pankaj is Web developer, Blogger, Learner, Tech and Music lover.

Follow on: Facebook | Twitter | Google | or

Comments and discussion
Have a doubt, write here. I will help my best.
Before commenting you must escape your source code before commenting. Paste your source code inside
<pre><code> ----Your Source Code---- </code></pre>