Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <cmath>
- using namespace std;
- void daDieci(unsigned __int64 numero, int base);
- unsigned __int64 daBaseA10(unsigned __int64 numero, int base);
- int main(int argc, char *argv[])
- {
- cout << "Conversione numerica da base a base arbitrarie" << endl << endl;
- int base1 = 0, base2 = 0;
- do
- {
- cout << "Inserire base di partenza (da 2 a 10): ";
- cin >> base1;
- } while (base1 < 2 || base1 > 10);
- do
- {
- cout << "Inserire base di arrivo (da 2 a 16): ";
- cin >> base2;
- } while (base2 < 2 || base2 > 16);
- unsigned __int64 numero;
- cout << "Inserire numero nella base di partenza: ";
- cin >> numero;
- if (base1 == 10)
- {
- daDieci(numero, base2);
- cin.get();
- }
- else
- {
- unsigned __int64 b10 = daBaseA10(numero, base1);
- daDieci(b10, base2);
- cin.get();
- }
- cin.get();
- return 0;
- }
- void daDieci(unsigned __int64 numero, int base)
- {
- if (base == 10)
- {
- cout << "Numero finale: " << numero;
- return;
- }
- if (!numero)
- {
- cout << "Numero finale: 0";
- return;
- }
- char buf[1024];
- memset(buf, 0, 1024);
- int curPos = 0;
- while (numero)
- {
- buf[curPos++] = (char) (numero % base);
- numero /= base;
- }
- curPos--;
- cout << "Numero finale: ";
- while (curPos >= 0)
- {
- if (base < 10)
- cout << (char) (buf[curPos--] + 0x30);
- else
- {
- if (buf[curPos] < 10)
- cout << (char) (buf[curPos--] + 0x30);
- else
- cout << (char) ((buf[curPos--] - 10) + 'A');
- }
- }
- cout << endl;
- }
- unsigned __int64 daBaseA10(unsigned __int64 numero, int base)
- {
- unsigned __int64 risultato = 0;
- int pos = 0;
- while (numero)
- {
- unsigned __int64 potenza = (unsigned __int64) ::pow((double) base, pos++);
- risultato += (numero % 10) * potenza;
- numero /= 10;
- }
- return risultato;
- }
Add Comment
Please, Sign In to add comment