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.
Example
Input
Input any number: 22
Output
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;
}
Output
Enter any number: 22 Original number = 22 (in decimal) Number after bits are flipped = -23 (in decimal)
Happy coding 😉
Recommended posts
- Bitwise operator programming exercises index.
- C program to count trailing zeros in a binary number.
- C program to count leading zeros in a binary number.
- C program to rotate bits of a numberr.
- C program to convert decimal to binary number system using bitwise operator.
- C program to swap two numbers using bitwise operator.