Is there a printf converter to print in binary format?

前端 未结 30 2664
盖世英雄少女心
盖世英雄少女心 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:56

    /* Convert an int to it's binary representation */
    
    char *int2bin(int num, int pad)
    {
     char *str = malloc(sizeof(char) * (pad+1));
      if (str) {
       str[pad]='\0';
       while (--pad>=0) {
        str[pad] = num & 1 ? '1' : '0';
        num >>= 1;
       }
      } else {
       return "";
      }
     return str;
    }
    
    /* example usage */
    
    printf("The number 5 in binary is %s", int2bin(5, 4));
    /* "The number 5 in binary is 0101" */
    

提交回复
热议问题