C++ - Decimal to binary converting

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

    In this approach, the decimal will be converted to the respective binary number in the string formate. The string return type is chosen since it can handle more range of input values.

    class Solution {
    public:
      string ConvertToBinary(int num) 
      {
        vector<int> bin;
        string op;
        for (int i = 0; num > 0; i++)
        {
          bin.push_back(num % 2);
          num /= 2;
        }
        reverse(bin.begin(), bin.end());
        for (size_t i = 0; i < bin.size(); ++i)
        {
          op += to_string(bin[i]);
        }
        return op;
      }
    };
    
    0 讨论(0)
  • 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 <bits/stdc++.h>
    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
    
    0 讨论(0)
  • 2020-11-28 19:31

    The conversion from natural number to a binary string:

    string toBinary(int n) {
        if (n==0) return "0";
        else if (n==1) return "1";
        else if (n%2 == 0) return toBinary(n/2) + "0";
        else if (n%2 != 0) return toBinary(n/2) + "1";
    }
    
    0 讨论(0)
  • 2020-11-28 19:31
    #include "stdafx.h"
    #include<iostream>
    #include<vector>
    #include<cmath>
    
    using namespace std;
    
    int main() {
        // Initialize Variables
        double x;
        int xOct;
        int xHex;
    
        //Initialize a variable that stores the order if the numbers in binary/sexagesimal base
        vector<int> rem;
    
        //Get Demical value
        cout << "Number (demical base): ";
        cin >> x;
    
        //Set the variables
        xOct = x;
        xHex = x;
    
        //Get the binary value
        for (int i = 0; x >= 1; i++) {
            rem.push_back(abs(remainder(x, 2)));
            x = floor(x / 2);
        }
    
        //Print binary value
        cout << "Binary: ";
        int n = rem.size();
        while (n > 0) {
            n--;
            cout << rem[n];
        } cout << endl;
    
        //Print octal base
        cout << oct << "Octal: " << xOct << endl;
    
        //Print hexademical base
        cout << hex << "Hexademical: " << xHex << endl;
    
        system("pause");
        return 0;
    }
    
    0 讨论(0)
  • 2020-11-28 19:31

    Your solution needs a modification. The final string should be reversed before returning:

    std::reverse(r.begin(), r.end());
    return r;
    
    0 讨论(0)
  • 2020-11-28 19:31

    using bitmask and bitwise and .

    string int2bin(int n){
        string x;
        for(int i=0;i<32;i++){
            if(n&1) {x+='1';}
            else {x+='0';}
            n>>=1;
        }
        reverse(x.begin(),x.end());
        return x;
    }
    
    0 讨论(0)
提交回复
热议问题