Is there a printf converter to print in binary format?

前端 未结 30 2807
盖世英雄少女心
盖世英雄少女心 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条回答
  •  猫巷女王i
    2020-11-21 06:50

    I optimized the top solution for size and C++-ness, and got to this solution:

    inline std::string format_binary(unsigned int x)
    {
        static char b[33];
        b[32] = '\0';
    
        for (int z = 0; z < 32; z++) {
            b[31-z] = ((x>>z) & 0x1) ? '1' : '0';
        }
    
        return b;
    }
    

提交回复
热议问题