C program to flip all bits of a binary number

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.

Required knowledge

Data Types in c, Input/Output in C, C Operators

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


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






Instagram