Is there a printf converter to print in binary format?

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

    Based on @William Whyte's answer, this is a macro that provides int8,16,32 & 64 versions, reusing the INT8 macro to avoid repetition.

    /* --- PRINTF_BYTE_TO_BINARY macro's --- */
    #define PRINTF_BINARY_PATTERN_INT8 "%c%c%c%c%c%c%c%c"
    #define PRINTF_BYTE_TO_BINARY_INT8(i)    \
        (((i) & 0x80ll) ? '1' : '0'), \
        (((i) & 0x40ll) ? '1' : '0'), \
        (((i) & 0x20ll) ? '1' : '0'), \
        (((i) & 0x10ll) ? '1' : '0'), \
        (((i) & 0x08ll) ? '1' : '0'), \
        (((i) & 0x04ll) ? '1' : '0'), \
        (((i) & 0x02ll) ? '1' : '0'), \
        (((i) & 0x01ll) ? '1' : '0')
    
    #define PRINTF_BINARY_PATTERN_INT16 \
        PRINTF_BINARY_PATTERN_INT8              PRINTF_BINARY_PATTERN_INT8
    #define PRINTF_BYTE_TO_BINARY_INT16(i) \
        PRINTF_BYTE_TO_BINARY_INT8((i) >> 8),   PRINTF_BYTE_TO_BINARY_INT8(i)
    #define PRINTF_BINARY_PATTERN_INT32 \
        PRINTF_BINARY_PATTERN_INT16             PRINTF_BINARY_PATTERN_INT16
    #define PRINTF_BYTE_TO_BINARY_INT32(i) \
        PRINTF_BYTE_TO_BINARY_INT16((i) >> 16), PRINTF_BYTE_TO_BINARY_INT16(i)
    #define PRINTF_BINARY_PATTERN_INT64    \
        PRINTF_BINARY_PATTERN_INT32             PRINTF_BINARY_PATTERN_INT32
    #define PRINTF_BYTE_TO_BINARY_INT64(i) \
        PRINTF_BYTE_TO_BINARY_INT32((i) >> 32), PRINTF_BYTE_TO_BINARY_INT32(i)
    /* --- end macros --- */
    
    #include 
    int main() {
        long long int flag = 1648646756487983144ll;
        printf("My Flag "
               PRINTF_BINARY_PATTERN_INT64 "\n",
               PRINTF_BYTE_TO_BINARY_INT64(flag));
        return 0;
    }
    

    This outputs:

    My Flag 0001011011100001001010110111110101111000100100001111000000101000
    

    For readability you may want to add a separator for eg:

    My Flag 00010110,11100001,00101011,01111101,01111000,10010000,11110000,00101000
    

提交回复
热议问题