Is there a printf converter to print in binary format?

前端 未结 30 2756
盖世英雄少女心
盖世英雄少女心 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条回答
  •  -上瘾入骨i
    2020-11-21 06:58

    Print Binary for Any Datatype

    // Assumes little endian
    void printBits(size_t const size, void const * const ptr)
    {
        unsigned char *b = (unsigned char*) ptr;
        unsigned char byte;
        int i, j;
        
        for (i = size-1; i >= 0; i--) {
            for (j = 7; j >= 0; j--) {
                byte = (b[i] >> j) & 1;
                printf("%u", byte);
            }
        }
        puts("");
    }
    

    Test:

    int main(int argv, char* argc[])
    {
        int i = 23;
        uint ui = UINT_MAX;
        float f = 23.45f;
        printBits(sizeof(i), &i);
        printBits(sizeof(ui), &ui);
        printBits(sizeof(f), &f);
        return 0;
    }
    

提交回复
热议问题