Is there a printf converter to print in binary format?

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

    Next will show to you memory layout:

    #include 
    #include 
    #include 
    
    using namespace std;
    
    template string binary_text(T dec, string byte_separator = " ") {
        char* pch = (char*)&dec;
        string res;
        for (int i = 0; i < sizeof(T); i++) {
            for (int j = 1; j < 8; j++) {
                res.append(pch[i] & 1 ? "1" : "0");
                pch[i] /= 2;
            }
            res.append(byte_separator);
        }
        return res;
    }
    
    int main() {
        cout << binary_text(5) << endl;
        cout << binary_text(.1) << endl;
    
        return 0;
    }
    

提交回复
热议问题