C program to flip all bits of a binary number

Write a C program to input any 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.

Example

Input

Input any number: 22

Output

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

Required knowledge

Basic C programming, Bitwise operator

To flip all bits of a number, C provides bitwise complement ~ operator. Here we will use the complement operator to flip bits of a number.

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 a 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;
}

Output

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

Happy coding 😉

Write your doubts or suggestion. I will try my best to help. You must escape source code before commenting. To format your source code paste your source code inside
<pre><code> ----Your Source Code---- </code></pre>