HomeAbout UsContact Us

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

By Jithin Tom
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.

Frequently Asked Questions

Why would an embedded developer need to reverse the bits of a word?

Bit reversal is common when interfacing with serial communication protocols that send the least significant bit (LSB) first instead of the most significant bit (MSB), or in Fast Fourier Transform (FFT) algorithms.

What is the time complexity of the loop-based bit reversal method?

The basic loop-based method runs in O(N) time where N is the bit width (32 iterations for a 32-bit word). For high-performance needs, developers use divide-and-conquer bitwise masks or hardware instructions like `RBIT` on ARM.

Does ARM architecture have a hardware instruction to reverse bits?

Yes, ARM Cortex-M processors support the `RBIT` assembly instruction, which reverses the bit order of a 32-bit register in a single CPU clock cycle, completely eliminating the need for loops.

Tags

embedded cbitwise operators

Share


Previous Article
Time and Space Complexity in Programming
Jithin Tom

Jithin Tom

A Closer Look at C/C++, RTOS, and Embedded Systems

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