Reversing the bits of an integer in C

Viewed 2196

I am trying to reverse the bits of an integer in the C program. Even though I have looked at the same question by another user, I was unable to understand most of the code that was written. I have noticed that the code I have is similar to the answer by Eregrith but I cannot identify the problem with my code below:

#include <stdio.h>
#include <stdlib.h>

unsigned int reverse_bits(unsigned int num)
{
unsigned int reverse_num = 0; /* initialize the result*/
unsigned int count = sizeof(unsigned int) * 8 - 1; /* counter to track the number of bits in the integer*/

while (num != 0)
{
    unsigned int last_bit = num & 1; /* get the right-most bit*/
    reverse_num = reverse_num | last_bit; /* add that bit to the right-most bit of the desired reversed bits*/
    reverse_num = reverse_num << 1; /* shift the reversed bits left*/
    num = num >> 1; /* shift the original bits right*/
    count--;
}
reverse_num = reverse_num << count; /* If the original bits have only 0
s then shift the remaining bits left*/

return reverse_num;
}

int main()
{

reverse_bits(1);
}

If I enter reverse_bits(1), the code returns -2147483648, which clearly did not reverse the bits of the integer 1. I am new to code and I am having difficulty locating the source of this error. Without having to change the entire code, how can I modify my existing code to return the correct output?

2 Answers
Related