Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "pch.h"
- #include <iostream>
- #include <string>
- using std::string;
- using std::endl;
- using std::cout;
- using std::cin;
- // Uppercase letters only
- string DecimalToBase(int number, int base) {
- string pattern = "0123456789ABCDEFGHIJKLMOPQRSTUVWXYZ";
- string result = "";
- while (number) {
- result = pattern[number % base] + result;
- number /= base;
- }
- return result;
- }
- int handleHelp(char c) {
- if (c >= 'A' & c <= 'Z')
- return c - 55;
- else if (c >= '0' && c <= '9')
- return c - 48; // '0';
- else return -1;
- }
- // Using Horner's method
- // returns - 1 when error occurs
- int BaseToDecimal(string number, int size, int curr_base) {
- int result = handleHelp(number[0]);
- if(handleHelp(number[0]) < 0) return -1;
- for (int i = 1; i < size; i++) {
- if(handleHelp(number[i]) < 0) return -1;
- result = result * curr_base + handleHelp(number[i]);
- }
- return result;
- }
- int main()
- {
- cout << "Program do zamiany systemow pozycyjnych.\n";
- int number, base;
- cout << "Podaj liczbe do zamiany: ";
- cin >> number;
- cout << "Podaj podstawe nowego systemu: ";
- cin >> base;
- string res = DecimalToBase(number, base);
- cout << "Liczba - " << number << " - w systemie o podstawie - " << base << " - wynosi: ";
- cout << res << endl;
- cout << "Twoja liczba to w systemie dziesietnym - " << BaseToDecimal(res, res.size(), base) << endl;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement