Is there a printf converter to print in binary format?

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

    Here is a quick hack to demonstrate the techniques for what you want.

    #include    /* printf */
    #include   /* strcat */
    #include   /* strtol */
    
    const char *byte_to_binary(int x)
    {
        static char b[9];
        b[0] = '\0';
    
        int z;
        for (z = 128; z > 0; z >>= 1) {
            strcat(b, ((x & z) == z) ? "1" : "0");
        }
    
        return b;
    }
    
    int main(void) {
        {
            /* binary string to int */
            char *tmp;
            char *b = "0101";
            printf("%d\n", strtol(b, &tmp, 2));
        }
        {
            /* byte to binary string */
            printf("%s\n", byte_to_binary(5));
        }
        return 0;
    }
    

提交回复
热议问题