-1

Came across a question to reverse bits of an unsigned integer. Tried a different approach. However, I'm not very familiar with how bit-wise operators work. Can someone please point what is fundamentally wrong here?

unsigned int reverse(unsigned int A)
{
unsigned int c=0;
int a=0;
while(a < 32)
{
    c = c << 1;
    c = c |  ( A & (1 << a) );
    a++;
}
return c;
ak9
  • 51
  • 6
  • In a case like this try simulating your code on pencil and paper. Step by step, statement by statement through the loop. To make it easier, assume that an "unsigned int" has only 8 bits and your loop header reads `while(a < 8)`. A few cycles through the loop and you should be able to figure it out. – davidbak Jun 24 '16 at 19:35
  • Possible duplicate of [Best Algorithm for Bit Reversal ( from MSB->LSB to LSB->MSB) in C](http://stackoverflow.com/questions/746171/best-algorithm-for-bit-reversal-from-msb-lsb-to-lsb-msb-in-c) –  Jun 24 '16 at 19:36
  • @davidbak i'll try it properly. @ vaxquis, it is not a duplicate since i didn't ask for any algorithm for reversal. – ak9 Jun 24 '16 at 20:01

1 Answers1

0

You shift 1 to the left in both cases and getting the same result. Try to use 10000... (32 bits) and shift it to the right instead of 1 << a

Alex Shutov
  • 3,217
  • 2
  • 13
  • 11