Is there a printf converter to print in binary format?

前端 未结 30 3503
盖世英雄少女心
盖世英雄少女心 2020-11-21 06:20

I can print with printf as a hex or octal number. Is there a format tag to print as binary, or arbitrary base?

I am running gcc.

printf(\"%d %x %o         


        
30条回答
  •  南旧
    南旧 (楼主)
    2020-11-21 06:58

    This code should handle your needs up to 64 bits. I created two functions: pBin and pBinFill. Both do the same thing, but pBinFill fills in the leading spaces with the fill character provided by its last argument. The test function generates some test data, then prints it out using the pBinFill function.

    #define kDisplayWidth 64
    
    char* pBin(long int x,char *so)
    {
      char s[kDisplayWidth+1];
      int i = kDisplayWidth;
      s[i--] = 0x00;  // terminate string
      do {  // fill in array from right to left
        s[i--] = (x & 1) ? '1' : '0';  // determine bit
        x >>= 1;  // shift right 1 bit
      } while (x > 0);
      i++;  // point to last valid character
      sprintf(so, "%s", s+i);  // stick it in the temp string string
      return so;
    }
    
    char* pBinFill(long int x, char *so, char fillChar)
    {
      // fill in array from right to left
      char s[kDisplayWidth+1];
      int i = kDisplayWidth;
      s[i--] = 0x00;  // terminate string
      do {  // fill in array from right to left
        s[i--] = (x & 1) ? '1' : '0';
        x >>= 1;  // shift right 1 bit
      } while (x > 0);
      while (i >= 0) s[i--] = fillChar;  // fill with fillChar 
      sprintf(so, "%s", s);
      return so;
    }
    
    void test()
    {
      char so[kDisplayWidth+1];  // working buffer for pBin
      long int val = 1;
      do {
        printf("%ld =\t\t%#lx =\t\t0b%s\n", val, val, pBinFill(val, so, '0'));
        val *= 11;  // generate test data
      } while (val < 100000000);
    }
    

    Output:

    00000001 =  0x000001 =  0b00000000000000000000000000000001
    00000011 =  0x00000b =  0b00000000000000000000000000001011
    00000121 =  0x000079 =  0b00000000000000000000000001111001
    00001331 =  0x000533 =  0b00000000000000000000010100110011
    00014641 =  0x003931 =  0b00000000000000000011100100110001
    00161051 =  0x02751b =  0b00000000000000100111010100011011
    01771561 =  0x1b0829 =  0b00000000000110110000100000101001
    19487171 = 0x12959c3 =  0b00000001001010010101100111000011
    

提交回复
热议问题