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.

Input any number: 22
Output number after bits are flipped: -23 (in decimal)

Required knowledge:

Basic C programming, Bitwise operator


Flipping bits of a binary number is simple and easy task in C. There is an operator provided by C language that handles the task of flipping bits or we may say complementing any number. C provides complement operator that flips all bits of the number and we will use the bitwise complement ~ operator to flip bits of a given number.


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

#include <stdio.h>

int main()
    int num, flippedNumber;

    //Reads 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;

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

Happy coding ;)

Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< pre>< code >----Your Source Code---- < / code > < / pre > (Remove spaces from pre and code tags)

No comments:

Post a Comment