Is there a printf converter to print in binary format?

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

    void print_ulong_bin(const unsigned long * const var, int bits) {
            int i;
    
            #if defined(__LP64__) || defined(_LP64)
                    if( (bits > 64) || (bits <= 0) )
            #else
                    if( (bits > 32) || (bits <= 0) )
            #endif
                    return;
    
            for(i = 0; i < bits; i++) { 
                    printf("%lu", (*var >> (bits - 1 - i)) & 0x01);
            }
    }
    

    should work - untested.

提交回复
热议问题