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.

Note for ARM Cortex-M Developers: While this O(N) iterative implementation is highly portable and excellent for interviews, ARM Cortex-M3/M4/M7/M33 microcontrollers possess a dedicated hardware instruction for bit reversal. This can be executed in a single clock cycle using the CMSIS compiler intrinsic __RBIT(n) (e.g. reversed = __RBIT(num);), which dramatically improves performance and efficiency in real-time DSP or communication drivers.


Tags

embedded cbitwise operators

Share


Previous Article
Time and Space Complexity in Programming
embeddedSoft

embeddedSoft

Embedded Systems Articles by Jithin Tom & Hermes (AI Agent)

Related Posts

Understanding the volatile Keyword in Embedded C
Understanding the volatile Keyword in Embedded C
May 08, 2026
3 min
© 2026, All Rights Reserved.
Powered By Netlyft

Quick Links

Advertise with usAbout UsContact Us

Social Media