C++ Bc. 15 cpp
#include <iostream> #include <string> #include <cctype> #include <algorithm> int prevod(std::string cislo, int zaklad) { int soucet = 0, mocnina=1; for (int i=cislo.size()-1; i>=0; i--) { const char znak = toupper(cislo[i]); int cislice = 0; // prevod znak ==> cislice lze efektivneji implementovat prevodni tabulkou switch (znak) { case 'F': cislice++; case 'E': cislice++; case 'D': cislice++; case 'C': cislice++; case 'B': cislice++; case 'A': cislice++; case '9': cislice++; case '8': cislice++; case '7': cislice++; case '6': cislice++; case '5': cislice++; case '4': cislice++; case '3': cislice++; case '2': cislice++; case '1': cislice++; } soucet += cislice*mocnina; mocnina *= zaklad; } return soucet; } std::string prevod(int cislo, int zaklad) { const std::string cislice = "0123456789ABCDEF"; std::string s; while (cislo) { int r = cislo % zaklad; s.push_back(cislice[r]); cislo /= zaklad; } // standardni funkce 'reverse' muze byt nahrazena cyklem // for (int i=0, j=s.size()-1; i<j; i++, j--) // { // char t = s[i]; s[i] = s[j]; s[j] = t; // } reverse(s.begin(), s.end()); return s; } int main() { using namespace std; int k, z, n; string s; cout << "prevod int ==> string : "; cout << prevod( "6B", 16) << " "; cout << prevod( "107", 10) << " "; cout << prevod( "153", 8) << " "; cout << prevod("1101011", 2) << "\n"; cout << "prevod string ==> int : "; cout << prevod(107, 16) << " "; cout << prevod(107, 10) << " "; cout << prevod(107, 8) << " "; cout << prevod(107, 2) << "\n"; }
výstup
prevod int ==> string : 107 107 107 107 prevod string ==> int : 6B 107 153 1101011
[ Zpět ]