C++ - Decimal to binary converting

后端 未结 29 3646
一向
一向 2020-11-28 18:53

I wrote a \'simple\' (it took me 30 minutes) program that converts decimal number to binary. I am SURE that there\'s a lot simpler way so can you show me? Here\'s the code:<

29条回答
  •  盖世英雄少女心
    2020-11-28 19:30

    My way of converting decimal to binary in C++. But since we are using mod, this function will work in case of hexadecimal or octal also. You can also specify bits. This function keeps calculating the lowest significant bit and place it on the end of the string. If you are not so similar to this method than you can vist: https://www.wikihow.com/Convert-from-Decimal-to-Binary

    #include 
    using namespace std;
    
    string itob(int bits, int n) {
        int c;
        char s[bits+1]; // +1 to append NULL character.
    
        s[bits] = '\0'; // The NULL character in a character array flags the end of the string, not appending it may cause problems.
    
        c = bits - 1; // If the length of a string is n, than the index of the last character of the string will be n - 1. Cause the index is 0 based not 1 based. Try yourself.
    
        do {
            if(n%2) s[c] = '1';
            else s[c] = '0';
            n /= 2;
            c--;
        } while (n>0);
    
        while(c > -1) {
            s[c] = '0';
            c--;
    }
    
        return s;
    }
    
    int main() {
        cout << itob(1, 0) << endl; // 0 in 1 bit binary.
        cout << itob(2, 1) << endl; // 1 in 2 bit binary.
        cout << itob(3, 2) << endl; // 2 in 3 bit binary.
        cout << itob(4, 4) << endl; // 4 in 4 bit binary.
        cout << itob(5, 15) << endl; // 15 in 5 bit binary.
        cout << itob(6, 30) << endl; // 30 in 6 bit binary.
        cout << itob(7, 61) << endl; // 61 in 7 bit binary.
        cout << itob(8, 127) << endl; // 127 in 8 bit binary.
        return 0;
    }
    

    The Output:

    0
    01
    010
    0100
    01111
    011110
    0111101
    01111111
    

提交回复
热议问题