Frage

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

War es hilfreich?

Lösung

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)

Andere Tipps

The result of a = (userInput&(1<<i)) will be either 1<<i or 0, (not 1 or 0). So change:

  if (a==1)

to:

  if (a != 0)

and your code should work.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top