Is there a printf converter to print in binary format?

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

    I liked the code by paniq, the static buffer is a good idea. However it fails if you want multiple binary formats in a single printf() because it always returns the same pointer and overwrites the array.

    Here's a C style drop-in that rotates pointer on a split buffer.

    char *
    format_binary(unsigned int x)
    {
        #define MAXLEN 8 // width of output format
        #define MAXCNT 4 // count per printf statement
        static char fmtbuf[(MAXLEN+1)*MAXCNT];
        static int count = 0;
        char *b;
        count = count % MAXCNT + 1;
        b = &fmtbuf[(MAXLEN+1)*count];
        b[MAXLEN] = '\0';
        for (int z = 0; z < MAXLEN; z++) { b[MAXLEN-1-z] = ((x>>z) & 0x1) ? '1' : '0'; }
        return b;
    }
    

提交回复
热议问题