C Programming

How to bit flip in C

Flipping a bit denotes switching or reversing the existing bit. The technique of analytically rearranging bits or other elements of data smaller than even a byte is known as bit manipulation. The C programming language is proficient at handling bits.

The bitwise operator operates with bits and carries out operations gradually. The shift operators execute the required transition from the left operator to the right operator. The appropriate operator has to be positive. The bits that have been left empty are replaced by zero.

We acquire a binary digit and shift its value towards the opponent whenever we reverse a bit. Let’s look at how to swap bits in C:

Using the bitwise operator to reverse every bit of an integer:

Toggling or reversing the existing bit state is considered flipping a bit. We would execute a loop starting 0 to the extent of the integer and swap each bit one at a time to reverse every element of binary values.

On the other hand, the C programming language offers a bitwise complement operator ~ that can be used for that task. Bitwise complement examines the component of argument bit. Whereas, if the operand’s appropriate value is 0, it converts to 1; or else, it assigns to 0. Here’s a C program that contains and reverses every element of a binary number with the help of a bitwise operator ~.

#include <stdio.h>
int main()
{
    int n, flippedNum;
    printf("Enter a number: ");
    scanf("%d", &n);
    flippedNum = ~n;
    printf("Actual number = %d (in decimal)\n", n);
    printf("Value after flipping the bits = %d (in decimal)", flippedNum);

    return 0;
}

In this example, first of all, we include the library . Then we call the main() function. Here we initialize two variables. One variable, ‘n’, has an integer data type, and the other variable, ‘flippednum,’ stores the value we want to flip.

In addition to this, we utilize the printf() function to display the statement ‘Enter a number’. So the user enters any value of his own choice. The scanf() method is being called. This method is used to state the configured data. We apply the ‘flippednum’ command so that the value entered by the user is being flipped. We flip the bits by using the bitwise complement sign ~.

In the next step, the printf() method is applied first to print the actual number, and then it prints the value after flipping the bits of the entered number. We end the program by return 0 command.

Use for loop to flip the bits:

We iterate through each of the bits of the number. We take an unsigned integer, flip every one of its elements, and get the integer having flipped bits in this scenario.

#include <stdio.h>
#include <stdlib.h>
unsigned int revBits(unsigned int n)
{
    unsigned int  NUMBER_OF_BITS = sizeof(n) * 8;
    unsigned int rev_num = 0, j, temp;
 
    for (j = 0; j < NUMBER_OF_BITS; j++)
    {
        temp = (n & (1 << j));
        if(temp)
            rev_num |= (1 << ((NUMBER_OF_BITS - 1) - j));
    }
    return rev_num;
}
int main()
{
    unsigned int a = 5;
    printf("%u", revBits(a));
    getchar();
}

Here, we are going to start the program by integrating the header files <stdio.h> and <stdlib.h>. Here we pass the ‘unsigned n’ variable, which has an integer data type. We declare a new variable that stores the number of bits. Here we multiply the size of the integer by 8. Then we initialize a variable ‘rev_num’ which stores the flipped number.

We also initialize a variable for the ‘for loop’ and ‘temp’ variables which temporarily holds the flipped value of the defined integer. In addition to this, we utilize a loop. We declare a variable ‘j’ within the loop and apply the condition on the variable that its value must be less than several bits. The last part of the for loop shows an increment in the value of variable ‘j’. Then we use the “if” condition on the ‘temp’ variable. This shows that if ‘rev_n’ is not equal to the number of bits, then the return statement returns the value of ‘rev_n’,

Further, the main() function is applied to test the above-mentioned method. Now we initialize the ‘unsigned a’ variable having integer data type. The printf() method now displays the value of the integer after reversing the bits. In the end, we employ the getchar() function. Here the getchar() method takes only one character as an argument.

Use while loop to flip the bits:

Here we have to keep adding the bits of an integer into reverse numbers till the integer equals zero. Swap the leftover bits of the reverse number once the defined number hits zero.

#include <stdio.h>
#include <stdlib.h>
unsigned int revBits(unsigned int n)
{
    unsigned int count = sizeof(n) * 8 - 2;
    unsigned int rev_n = n;
    n >>= 2;
    while(n)
    {
       rev_n <>= 2;
       count--;
    }
    rev_n <<= count;
    return rev_n;
}  
int main()
{
    unsigned int a = 7;
    printf("%u", revBits(a));
    getchar();
}

At the beginning of the program, we incorporate the header files <stdio.h> and <stdlib.h>. Then we define a function that reverses the bits. The variable ‘unsigned n’ has an integer data type; thus, we provide it here. We create a new variable to retain the count of the number of bits. The size of the integer is multiplied by eight in this case. Then, we acquire a variable called ‘rev_num’ to hold the flipped number.

We additionally built a variable for the while loop and applied the condition on this variable. In addition to this, we utilize a while loop. Within the while loop, we employ the condition that if the ‘rev_n’ is less than or equal to 2 or if the ‘rev_n’ is not equal to the value of ‘n’, we decrease the count. That’s how we get the value of ‘’rev_n’.

Now, we apply the main() function, and here we’ll initialize the variable ‘unsigned a’ by setting the value of this variable. This variable’s data type is an integer. After reversing the bits, the printf() method returns the result. Furthermore, we have used the getchar() function.

Conclusion:

In this article, we have examined the methods of flipping the bits in the C language. In the first situation, we take any integer from the user, and then we utilize the bitwise operator ~ to reverse all the bits of the defined number. Then we observe how to flip the bits by using for and while loop.

About the author

Kalsoom Bibi

Hello, I am a freelance writer and usually write for Linux and other technology related content