Guest User

Untitled

a guest
Jan 24th, 2018
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.78 KB | None | 0 0
  1. #include <iostream>
  2. #include <cmath>
  3.  
  4. using namespace std;
  5.  
  6. void daDieci(unsigned __int64 numero, int base);
  7. unsigned __int64 daBaseA10(unsigned __int64 numero, int base);
  8.  
  9. int main(int argc, char *argv[])
  10. {
  11.     cout << "Conversione numerica da base a base arbitrarie" << endl << endl;
  12.  
  13.     int base1 = 0, base2 = 0;
  14.  
  15.     do
  16.     {
  17.         cout << "Inserire base di partenza (da 2 a 10): ";
  18.         cin >> base1;
  19.     } while (base1 < 2 || base1 > 10);
  20.  
  21.     do
  22.     {
  23.         cout << "Inserire base di arrivo (da 2 a 16): ";
  24.         cin >> base2;
  25.     } while (base2 < 2 || base2 > 16);
  26.  
  27.     unsigned __int64 numero;
  28.  
  29.     cout << "Inserire numero nella base di partenza: ";
  30.     cin >> numero;
  31.  
  32.     if (base1 == 10)
  33.     {
  34.         daDieci(numero, base2);
  35.         cin.get();
  36.     }
  37.     else
  38.     {
  39.         unsigned __int64 b10 = daBaseA10(numero, base1);
  40.         daDieci(b10, base2);
  41.         cin.get();
  42.     }
  43.  
  44.     cin.get();
  45.  
  46.     return 0;
  47. }
  48.  
  49. void daDieci(unsigned __int64 numero, int base)
  50. {
  51.     if (base == 10)
  52.     {
  53.         cout << "Numero finale: " << numero;
  54.         return;
  55.     }
  56.    
  57.     if (!numero)
  58.     {
  59.         cout << "Numero finale: 0";
  60.         return;
  61.     }
  62.  
  63.     char buf[1024];
  64.     memset(buf, 0, 1024);
  65.  
  66.     int curPos = 0;
  67.     while (numero)
  68.     {
  69.         buf[curPos++] = (char) (numero % base);
  70.         numero /= base;
  71.     }
  72.  
  73.     curPos--;
  74.  
  75.     cout << "Numero finale: ";
  76.     while (curPos >= 0)
  77.     {
  78.         if (base < 10)
  79.             cout << (char) (buf[curPos--] + 0x30);
  80.         else
  81.         {
  82.             if (buf[curPos] < 10)
  83.                 cout << (char) (buf[curPos--] + 0x30);
  84.             else
  85.                 cout << (char) ((buf[curPos--] - 10) + 'A');
  86.         }
  87.     }
  88.  
  89.     cout << endl;
  90. }
  91.  
  92. unsigned __int64 daBaseA10(unsigned __int64 numero, int base)
  93. {
  94.     unsigned __int64 risultato = 0;
  95.     int pos = 0;
  96.     while (numero)
  97.     {
  98.         unsigned __int64 potenza = (unsigned __int64) ::pow((double) base, pos++);
  99.         risultato += (numero % 10) * potenza;
  100.         numero /= 10;
  101.     }
  102.  
  103.     return risultato;
  104. }
Add Comment
Please, Sign In to add comment