简体   繁体   English

在c中打印二进制字符

[英]Printing binary char in c

I cannot, for the love of myself figure out what the logic is behind this C code. 我不能,因为对自己的爱,弄清楚这个C代码背后的逻辑是什么。

Supposedly, the following should print out the binary representation of an unsigned char x, and we are only allowed to fill in the blanks. 据推测,下面应该打印出unsigned char x的二进制表示,我们只允许填空。

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? 我的意思是现在,第一个条件检查128是否<= char,但不是unsigned char,是什么,255个字节? So why is it only printing '1' in it. 那么为什么它只打印'1'。

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 . b的二进制表示为10000000 By doing b >> 1 and checking b <= x we can check each bit on x is 1 or 0 . 通过执行b >> 1并检查b <= x我们可以检查x上的每个位是1还是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. 因此,代码尝试在每次循环迭代时仅测试最重要的“1”位。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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