Search code examples
cbit-manipulationbitputchar

bitwise operation, printing of bits depends of which putchar is put first...?


I'm simply trying to print an unsigned int as bits, but it appears my code:

void checksWithOne(unsigned int userInput)
{
   int i = 0, a = 0;

   for (i = sizeof(int)*8-1; i >= 0; i--)
   {
      a = (userInput&(1<<i));
      if (a==1)
      {
         putchar('1');
      }
      else
      {
         putchar('0');
      }
   }
   printf("\n");
}

Only works if the if statement is changed as such (replacing 1s and 0s):

      if (a==0)
      {
         putchar('0');
      }
      else
      {
         putchar('1');
      }

It's beyond me as to why that is... any thoughts?

Thanks


Solution

  • Second code works because you prints '0' when a is == 0 else '1'. Accordingly in first code piece, if(a==1) should be if(a) that means print 1 if a is not 0 (Rremember every non-zero value is true in C).

    The thing is a = (userInput & (1<<i)); is not always 1 but a can be a number that is either zero or a number in which only one bit is one (e.g. ...00010000)