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?
printf()
to print your result, you want to use%d
for integer and%u
for unsigned integer.-2147483648
that you are mentioning? You are usingunsigned int
, you shouldn't see any negative number, unless you are mixingint
andunsigned int
by mistake, which I don't see anywhere in your code.reverse_bits
function. Where is the code that generated your output on which you base your conclusion?8
come from? Did you meanCHAR_BIT
?