C Program to Reverse All Bits of an 32-bit Integer using Bitwise

«
»

This is a C Program to reverse all the bits of an 32-bit integer using bitwise.

Problem Description

This C Program reverse all the bits of an 32-bit integer using bitwise.

Problem Solution

Take input from the user and performs bitwise operations as shown in the program below.

Program/Source Code

Here is source code of the C Program to reverse all the bits of an 32-bit integer using bitwise. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

/*
 * C Program to Reverse all the Bits of an 32-bit Integer using 
 * Bitwise 
 */
#include <stdio.h>
 
int main ()
{
	int n = 0, num = 0, count = 0, rev_bits = 0;
	printf ("Enter the number: ");
	scanf ("%d", &n);
 
	while (n > 0)
	{
		// keep shifting each bit
		rev_bits = rev_bits << 1;
 
		// if the bit is 1 then we XOR with 1
		if (n & 1 == 1)
		{
			rev_bits = rev_bits ^ 1;
		}
 
		// right shift n
		n = n >> 1;
	}
 
	printf ("\nThe reversed resultant = %d\n", rev_bits);
 
	return 0;
}
Program Explanation

1. Take the input from the user and store it in “n” variable.
2. For a given integer n, the basic idea is to loop through each bit of ‘n’ from right end (right-shift) and keep shifting ‘rev_bits’ from left end (left-shift).
rev_bits = rev_bits << 1; n = n >> 1;
3. In while looping if a set bit is encountered, then set the bit in rev_bits. Perform loop for all bits. At the end ‘rev_bits’ contain the resultant reverse.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
advertisement
advertisement
Runtime Test Cases

Test case 1 – Here, the entered number is 2.

Enter the number: 2
 
The reversed resultant = 1

Test case 2 – Here, the entered number is 7.

Enter the number: 7
 
The reversed resultant = 7

Test case 3 – Here, the entered number is 256

Enter the number: 256
 
The reversed resultant = 1

Sanfoundry Global Education & Learning Series – 1000 C Programs.

advertisement

Here’s the list of Best Books in C Programming, Data-Structures and Algorithms

If you wish to look at programming examples on all topics, go to C Programming Examples.

advertisement

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & technical discussions at Telegram SanfoundryClasses.