Is there a printf converter to print in binary format?

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

    One statement generic conversion of any integral type into the binary string representation using standard library:

    #include 
    MyIntegralType  num = 10;
    print("%s\n",
        std::bitset(num).to_string().insert(0, "0b").c_str()
    ); // prints "0b1010\n"
    

    Or just: std::cout << std::bitset(num);

提交回复
热议问题