Is there a printf converter to print in binary format?

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

    My solution:

    long unsigned int i;
    for(i = 0u; i < sizeof(integer) * CHAR_BIT; i++) {
        if(integer & LONG_MIN)
            printf("1");
        else
            printf("0");
        integer <<= 1;
    }
    printf("\n");
    
    0 讨论(0)
  • 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 <stdio.h>
    
    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

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
  • 2020-11-21 06:50

    No standard and portable way.

    Some implementations provide itoa(), but it's not going to be in most, and it has a somewhat crummy interface. But the code is behind the link and should let you implement your own formatter pretty easily.

    0 讨论(0)
  • 2020-11-21 06:51

    Maybe a bit OT, but if you need this only for debuging to understand or retrace some binary operations you are doing, you might take a look on wcalc (a simple console calculator). With the -b options you get binary output.

    e.g.

    $ wcalc -b "(256 | 3) & 0xff"
     = 0b11
    
    0 讨论(0)
提交回复
热议问题