Tuesday, June 10, 2008

Reverse the bits in a number

The problem is to reverse the bits in a number.
Example : 1011 should be reversed as 1101


#include <stdio.h>
void bit_form(unsigned int value)
{
while(value)
{
printf("%d", value & 0x01);
value = value >>1;
}
printf("\n");
return;
}
int main()
{
unsigned int value = 0;
scanf("%d", &value);
unsigned int return_value = value;
int loop = sizeof(value) * CHAR_BIT - 1;

bit_form(value);

for(value >>= 1; value; value >>= 1)
{
return_value <<= 1;
return_value |= value & 1;
loop--;
}

return_value <<= loop;
bit_form(return_value);
return 0;
}

No comments:

Post a Comment