HomeAbout UsContact Us

C Program to reverse bits in a 32-bit unsigned word

By embeddedSoft
Published in Embedded C/C++
September 07, 2025
1 min read
C Program to reverse bits in a 32-bit unsigned word

C Program

#include <stdio.h>
#include <stdint.h>
// Function to reverse bits of a 32-bit unsigned integer
uint32_t reverseBits(uint32_t n) {
uint32_t result = 0;
for (int i = 0; i < 32; i++) {
result <<= 1; // Shift result left
result |= (n & 1); // Copy LSB of n into result
n >>= 1; // Shift n right
}
return result;
}
int main() {
uint32_t num, reversed;
printf("Enter a 32-bit unsigned integer: ");
scanf("%u", &num);
reversed = reverseBits(num);
printf("Original number (decimal): %u\n", num);
printf("Reversed bits (decimal): %u\n", reversed);
printf("Original number (hex): 0x%08X\n", num);
printf("Reversed bits (hex): 0x%08X\n", reversed);
return 0;
}

Code Walkthrough

The function reverseBits iterates 32 times (for each bit).

In each step:

  • The result is shifted left to make space.
  • The least significant bit (LSB) of n is appended to result.
  • Then n is shifted right to process the next bit.

Tags

embedded cbitwise operators

Share


Previous Article
Time and Space Complexity in Programming
embeddedSoft

embeddedSoft

Insightful articles on embedded systems

Related Posts

C program to swap the rows-to-columns for any square matrix
C program to swap the rows-to-columns for any square matrix
September 08, 2025
1 min
© 2025, All Rights Reserved.
Powered By Netlyft

Quick Links

Advertise with usAbout UsContact Us

Social Media