Is there a printf converter to print in binary format?

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

    None of the previously posted answers are exactly what I was looking for, so I wrote one. It is super simple to use %B with the printf!

    /*
     * File:   main.c
     * Author: Techplex.Engineer
     *
     * Created on February 14, 2012, 9:16 PM
     */
    
    #include 
    #include 
    #include 
    #include 
    #include 
    
    static int printf_arginfo_M(const struct printf_info *info, size_t n, int *argtypes)
    {
        /* "%M" always takes one argument, a pointer to uint8_t[6]. */
        if (n > 0) {
            argtypes[0] = PA_POINTER;
        }
        return 1;
    }
    
    static int printf_output_M(FILE *stream, const struct printf_info *info, const void *const *args)
    {
        int value = 0;
        int len;
    
        value = *(int **) (args[0]);
    
        // Beginning of my code ------------------------------------------------------------
        char buffer [50] = "";  // Is this bad?
        char buffer2 [50] = "";  // Is this bad?
        int bits = info->width;
        if (bits <= 0)
            bits = 8;  // Default to 8 bits
    
        int mask = pow(2, bits - 1);
        while (mask > 0) {
            sprintf(buffer, "%s", ((value & mask) > 0 ? "1" : "0"));
            strcat(buffer2, buffer);
            mask >>= 1;
        }
        strcat(buffer2, "\n");
        // End of my code --------------------------------------------------------------
        len = fprintf(stream, "%s", buffer2);
        return len;
    }
    
    int main(int argc, char** argv)
    {
        register_printf_specifier('B', printf_output_M, printf_arginfo_M);
    
        printf("%4B\n", 65);
    
        return EXIT_SUCCESS;
    }
    

提交回复
热议问题