Print Reverse Bits

I've gotten this program working well except for a problem in the reverseBits function that I'm having trouble with. The program asks the user for an integer input, takes it and outputs the binary value and the binary value in reverse order. It should output like this example:
12 = 00000000 00000000 00000000 00001100
and:
12 = 00110000 00000000 00000000 00000000
I've gotten the reverse on the correct side, but outputs like this:
12 = 11110000 00000000 00000000 00000000
or:
4 = 11100000 00000000 00000000 00000000
Any idea what could be causing it to do that?




#include

void displayBits(unsigned value);
void reverseBits(unsigned reverse);

int main(void)
{
unsigned x;

printf("Enter an Integer: ");
scanf("%u", &x);

displayBits(x);
reverseBits(x);

return 0;
}

void displayBits(unsigned value)
{
unsigned c;
unsigned displayMask = 1 << 31;

printf("%10u = ", value);

for(c = 1; c <= 32; c++)
{
putchar(value & displayMask ? '1' : '0');
value <<= 1;

if (c %8 == 0)
{
putchar(' ');
}
}
putchar('
');
}

void reverseBits(unsigned reverse)
{
unsigned c;
unsigned displayMask = 31 >> 1 ;

printf("%10u = ", reverse);

for(c = 1; c <= 32; c++)
{
putchar(reverse & displayMask ? '1' : '0');
reverse >>= 1 ;

if (c %8 == 0)
{
putchar(' ');
}
}
putchar('
');
}
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories