Is there a printf converter to print in binary format?

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

    void
    print_binary(unsigned int n)
    {
        unsigned int mask = 0;
        /* this grotesque hack creates a bit pattern 1000... */
        /* regardless of the size of an unsigned int */
        mask = ~mask ^ (~mask >> 1);
    
        for(; mask != 0; mask >>= 1) {
            putchar((n & mask) ? '1' : '0');
        }
    
    }
    

提交回复
热议问题