Is there a printf converter to print in binary format?

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

    Here's a version of the function that does not suffer from reentrancy issues or limits on the size/type of the argument:

    #define FMT_BUF_SIZE (CHAR_BIT*sizeof(uintmax_t)+1)
    
    char *binary_fmt(uintmax_t x, char buf[static FMT_BUF_SIZE])
    {
        char *s = buf + FMT_BUF_SIZE;
        *--s = 0;
        if (!x) *--s = '0';
        for (; x; x /= 2) *--s = '0' + x%2;
        return s;
    }
    

    Note that this code would work just as well for any base between 2 and 10 if you just replace the 2's by the desired base. Usage is:

    char tmp[FMT_BUF_SIZE];
    printf("%s\n", binary_fmt(x, tmp));
    

    Where x is any integral expression.

提交回复
热议问题