1

I cannot, for the love of myself figure out what the logic is behind this C code.

Supposedly, the following should print out the binary representation of an unsigned char x, and we are only allowed to fill in the blanks.

void print_binary(unsigned char x) {
    int b = 128;

    while (__________________) {

        if (b <= x) {
            x -= b;
            printf("1");
        } else
            printf("0");

        ______________________;
    }
}

Of course I could game the program by simply ignoring the lines above. However I'm under the impression that this is not really the way to do things (it's more of a hack).

I mean really now, the first condition checks whether 128 is <= the char, but isn't an unsigned char, what, 255 bytes? So why is it only printing '1' in it.

Perhaps I'm missing something quite obvious (not really a c programmer) but the logic just doesn't sink into me this time.

Can anyone point me in the right direction? And if you can give me a clue without completely saying the answer, that would be heavenly.

Secret
  • 3,291
  • 3
  • 32
  • 50
  • 3
    The second blank is probably `b /= 2`; the first is presumably `b != 0`. – Jonathan Leffler Sep 02 '13 at 06:18
  • 3
    I invite you to look to the list on the right/left of Related questions. and pick [this one](http://stackoverflow.com/questions/111928/is-there-a-printf-converter-to-print-in-binary-format?rq=1). Further, "but isn't an unsigned char, what, 255 bytes" ?? I dunno about your platform, but on mine an unsigned char is *one* byte. – WhozCraig Sep 02 '13 at 06:18
  • 2
    This question is more about maths than about C. – Joni Sep 02 '13 at 06:21
  • @Joni My exact feeling - which is weird since this is supposed to be an "Are you familiar enough with C?" test. – Secret Sep 02 '13 at 06:24

3 Answers3

3
void print_binary(unsigned char x) {
    int b = 128;

    while (b != 0) {

        if (b <= x) {
            x -= b;
            printf("1");
        } else
            printf("0");

        b = b >> 1;
    }
}

The binary representaion for b is 10000000. By doing b >> 1 and checking b <= x we can check each bit on x is 1 or 0.

Thanushan
  • 532
  • 2
  • 8
1

You wanted only a clue: Value of the current bit is always bigger, than the combination of less significant bits after it. Thus code tries to test only the most significant '1'-bit on each iteration of loop.

user694733
  • 15,208
  • 2
  • 42
  • 68
0

If we disregard the original code, the most intuitive way to do this would be:

void print_binary (uint8_t x) 
{
  for(uint8_t mask=0x80; mask!=0; mask>>=1)
  {
    if(x & mask)
    {
      printf("1");
    }
    else
    {
      printf("0");
    }
  }
  printf("\n");
}
Lundin
  • 195,001
  • 40
  • 254
  • 396