pclovechristian

Binary Conversion

Mar 16th, 2012
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.45 KB | None | 0 0
  1. #include <iostream>
  2. #include <String>
  3.  
  4. using namespace std;
  5.  
  6. void DecToBin(int num, int base);
  7. double rem;
  8. int final[99];
  9. int i = 0.0;
  10.  
  11. int main()
  12. {
  13.     double DecimalNum, base;
  14.     cout << "Welcome to Binary conversion program!" << endl;
  15.  
  16.     cout << "Enter your base: ";
  17.     cin >> base;
  18.             while (base < 2 || base > 35)
  19.             {
  20.             cout << "Between 2~35 please :)" << endl;
  21.             while(!(cin >> base)) // Loops that goes on until cin fails
  22.         {
  23.  
  24.             cin.clear(); // if fails, clear the failed flag.
  25.             while(cin.get() != '\n'){} // A loop the cleans out anything that is left over in the input stream.
  26.  
  27.             cout << "Only numbers please: " << endl << "What's the base again? " <<endl;// Output failed prompt. And requires only numbers
  28.         }
  29.             }
  30.  
  31.  
  32.     cout << "Enter number in decimal: ";
  33.     cin >> DecimalNum;
  34.  
  35.     DecToBin(DecimalNum, base);
  36.     return 0;
  37. }
  38.  
  39.     void DecToBin(int num, int base)
  40. {
  41.     while (num != 0)
  42.     {
  43.         rem = (num%base);
  44.  
  45.         final[i] = rem;
  46.         i++;
  47.  
  48.         num = num/base;
  49.     }
  50.             for (i--; i>-1; i--)
  51.             {
  52.                 if (final[i]<10) // if the remainder goes up to 10 then it changes the value to letters..
  53.  
  54.                 cout << final[i];
  55.  
  56.                 else
  57.  
  58.                 cout << char(final[i]-10+'a');
  59.             }
  60.             num = 1;
  61.             cout << endl;
  62.  
  63.     }
Advertisement
Add Comment
Please, Sign In to add comment