Is there a printf converter to print in binary format?

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

    Print the least significant bit and shift it out on the right. Doing this until the integer becomes zero prints the binary representation without leading zeros but in reversed order. Using recursion, the order can be corrected quite easily.

    #include 
    
    void print_binary(unsigned int number)
    {
        if (number >> 1) {
            print_binary(number >> 1);
        }
        putc((number & 1) ? '1' : '0', stdout);
    }
    

    To me, this is one of the cleanest solutions to the problem. If you like 0b prefix and a trailing new line character, I suggest wrapping the function.

    Online demo

提交回复
热议问题