简体   繁体   中英

Printing binary char in c

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 ac 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.

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 .

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.

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");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM