C++ - Decimal to binary converting

后端 未结 29 3467
一向
一向 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:42

    Here are two approaches. The one is similar to your approach

    #include <iostream>
    #include <string>
    #include <limits>
    #include <algorithm>
    
    int main()
    {
        while ( true )
        {
            std::cout << "Enter a non-negative number (0-exit): ";
    
            unsigned long long x = 0;
            std::cin >> x;
    
            if ( !x ) break;
    
            const unsigned long long base = 2;
    
            std::string s;
            s.reserve( std::numeric_limits<unsigned long long>::digits ); 
    
            do { s.push_back( x % base + '0' ); } while ( x /= base );
    
            std::cout << std::string( s.rbegin(), s.rend() )  << std::endl;
        }
    }
    

    and the other uses std::bitset as others suggested.

    #include <iostream>
    #include <string>
    #include <bitset>
    #include <limits>
    
    int main()
    {
        while ( true )
        {
            std::cout << "Enter a non-negative number (0-exit): ";
    
            unsigned long long x = 0;
            std::cin >> x;
    
            if ( !x ) break;
    
            std::string s = 
                std::bitset<std::numeric_limits<unsigned long long>::digits>( x ).to_string();
    
            std::string::size_type n = s.find( '1' ); 
            std::cout << s.substr( n )  << std::endl;
        }
    }
    
    0 讨论(0)
  • 2020-11-28 19:43

    DECIMAL TO BINARY NO ARRAYS USED *made by Oya:

    I'm still a beginner, so this code will only use loops and variables xD...

    Hope you like it. This can probably be made simpler than it is...

        #include <iostream>
        #include <cmath>
        #include <cstdlib>
    
        using namespace std;
    
        int main()
        {
            int i;
            int expoentes; //the sequence > pow(2,i) or 2^i
            int decimal; 
            int extra; //this will be used to add some 0s between the 1s
            int x = 1;
    
            cout << "\nThis program converts natural numbers into binary code\nPlease enter a Natural number:";
            cout << "\n\nWARNING: Only works until ~1.073 millions\n";
            cout << "     To exit, enter a negative number\n\n";
    
            while(decimal >= 0){
                cout << "\n----- // -----\n\n";
                cin >> decimal;
                cout << "\n";
    
                if(decimal == 0){
                    cout << "0";
                }
                while(decimal >= 1){
                    i = 0;
                    expoentes = 1;
                    while(decimal >= expoentes){
                        i++;
                        expoentes = pow(2,i);
                    }
                    x = 1;
                    cout << "1";
                    decimal -= pow(2,i-x);
                    extra = pow(2,i-1-x);
                    while(decimal < extra){
                        cout << "0";
                        x++;
                        extra = pow(2,i-1-x);
                    }
                }
            }
            return 0;
        }
    
    0 讨论(0)
  • 2020-11-28 19:43

    For this , In C++ you can use itoa() function .This function convert any Decimal integer to binary, decimal , hexadecimal and octal number.

    #include<bits/stdc++.h>
    using namespace std;
    int main(){
     int a;    
     char res[1000];
     cin>>a;
     itoa(a,res,10);
     cout<<"Decimal- "<<res<<endl;
     itoa(a,res,2);
     cout<<"Binary- "<<res<<endl;
     itoa(a,res,16);
     cout<<"Hexadecimal- "<<res<<endl;
     itoa(a,res,8);
     cout<<"Octal- "<<res<<endl;return 0;
    }
    

    However, it is only supported by specific compilers.

    You can see also: itoa - C++ Reference

    0 讨论(0)
  • 2020-11-28 19:46

    The following is a recursive function which takes a positive integer and prints its binary digits to the console.

    Alex suggested, for efficiency, you may want to remove printf() and store the result in memory... depending on storage method result may be reversed.

    /**
     * Takes a unsigned integer, converts it into binary and prints it to the console.
     * @param n the number to convert and print
     */
    void convertToBinary(unsigned int n)
    {
        if (n / 2 != 0) {
            convertToBinary(n / 2);
        }
        printf("%d", n % 2);
    }
    

    Credits to UoA ENGGEN 131

    *Note: The benefit of using an unsigned int is that it can't be negative.

    0 讨论(0)
  • 2020-11-28 19:46

    Non recursive solution:

    #include <iostream>
    #include<string>
    
    
    std::string toBinary(int n)
    {
        std::string r;
        while(n!=0) {r=(n%2==0 ?"0":"1")+r; n/=2;}
        return r;
    }
    int main()
    {
        std::string i= toBinary(10);
        std::cout<<i;
    }
    

    Recursive solution:

    #include <iostream>
    #include<string>
    
    std::string r="";
    std::string toBinary(int n)
    {
        r=(n%2==0 ?"0":"1")+r;
        if (n / 2 != 0) {
            toBinary(n / 2);
        }
        return r;
    }
    int main()
    {
        std::string i=toBinary(10);
        std::cout<<i;
    }
    
    0 讨论(0)
  • 2020-11-28 19:47
    std::string bin(uint_fast8_t i){return !i?"0":i==1?"1":bin(i/2)+(i%2?'1':'0');}
    
    0 讨论(0)
提交回复
热议问题