Prevod z dvojkove soustavy
int main()
{
string s = "101011";
int len = s.length();
int v = 0; // vysledek
for (int i = 0; i < len; i++)
{
char c = s[i];
v = 2 * v; // posunout, pridat na konec nulu
if (c == '1')
v = v + 1;
}
cout << s << " ... " << v << endl;
int main()
{
int v = 22; // vstup
string s = ""; // vystupni text
int n = v;
while (n > 0)
{
if (n % 2 == 0)
s = "0" + s;
else
s = "1" + s;
n = n / 2;
}
if (v == 0) s = "0"; // pro nulu na vstupu byl vysledkem prazdny retezec
cout << v << " ... " << s << endl;
}
Prevod do dvojkove soustavy
#include
using namespace std;
int main()
{
string s = "Ff";
int len = s.length();
int v = 0; // vysledek
int base = 16; // zaklad ciselne soustavy
for (int i = 0; i < len; i++)
{
char c = s[i];
v = v * base; // posunout, pridat na konec nulu
int d = 99;
if (c >= '0' && c <= '9')
{
d = c - '0';
}
else if (c >= 'A' && c <= 'Z')
{
d = c - 'A' + 10;
}
else if (c >= 'a' && c <= 'z')
{
d = c - 'a' + 10;
}
if (d >= base) cout << "spatna cislice " << c << endl;
v = v + d;
}
cout << s << " ... " << v << endl;
}
#include
using namespace std;
int main()
{
int v = 42; // vstup
string s = ""; // vystupni text
int base = 10;
int n = v;
while (n > 0)
{
int d = n % base; // jedna cislice
char c;
if (d <= 9)
c = '0' + d; // jedno pismeno
else
c = 'a' + d - 10; // d=10 => c='a'
s = c + s; // pridat na zacatek
n = n / base; // odstranit nejnizsi cislici
}
if (v == 0) s = "0"; // pro nulu na vstupu byl vysledkem prazdny retezec
cout << v << " ... " << s << endl;
}