Advertisement
makispaiktis

Decimal to Binary

Apr 20th, 2019 (edited)
317
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.51 KB | None | 0 0
  1. #include <iostream>
  2. #include <math.h>
  3. #include <vector>
  4. #include <algorithm>
  5.  
  6. using namespace std;
  7.  
  8. void displayVector(vector <int> v){
  9.     for(unsigned i=0; i<v.size(); i++){
  10.         cout << v[i];
  11.     }
  12.     //cout << endl;
  13. }
  14.  
  15. int main()
  16. {
  17.     // 1. Intro
  18.     menu:
  19.     cout << "Give me a natural number (in decimal system) to convert it into binary:\n";
  20.     double input;
  21.     cin >> input;
  22.  
  23.     // 2. Convert to integer in case of error
  24.     int n = int(fabs(input));
  25.     int numOfDigits = int(log2(n)) + 1;
  26.     //cout << numOfDigits << endl;
  27.     //cout << "Logs: " << log(n) << " / " << log(2) << " = " << log(n) / log(2) << " ----> " << int(log(n) / log(2)) + 1 << endl;
  28.     cout << "Decimal: " << n << endl;
  29.  
  30.     // 3. Check the case of 0 or the overflow case
  31.     if(n == 0){
  32.         cout << "Binary : 0 (No specified number of digits)" << endl << endl;
  33.         goto menu;
  34.     }
  35.     if(n > 1000000000){
  36.         cout << "Cannot make calculations with numbers higher than: " << 1000000000 << endl << endl;
  37.         return -1000;
  38.     }
  39.  
  40.     // 4. Search the digits
  41.     vector <int> digits = vector <int> ();
  42.     int sum = n;
  43.     for(int i=numOfDigits-1; i>=0; i--){
  44.         if(sum >= pow(2, i)){
  45.             digits.push_back(1);
  46.             sum -= pow(2, i);
  47.         }
  48.         else{
  49.             digits.push_back(0);
  50.         }
  51.     }
  52.  
  53.     cout << "Binary : ";
  54.     displayVector(digits);
  55.     cout << "  (" << numOfDigits << " digits)";
  56.     cout << endl << endl;
  57.     goto menu;
  58.  
  59.     return 0;
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement