D
Erstmal, was verstehst Du in diesem Zusammenhang unter einer "Dezimalzahl" und einer "Binärzahl"?
Eine** int **Variable enthält ja erst mal einen Zahlenwert, der völlig unabhängig von einer bestimmten Darstellung (sei es nun als Dezimalzahl, als Hexadezimalzahl oder als Binär-String) ist.
Intern, also im Arbeitsspeicher, sind die Daten letztendlich natürlich immer binär kodiert (im Zweierkomplement), niemals dezimal.
So wie ich Deinen Code verstehe, versucht Du also den** int Wert so umzuformen, dass eine Darstellung als Dezimalzahl (zum Beispiel printf() mit %d **Platzhalter), einen Binär-String ergibt...
Ist das richtig?
Es wäre für mich irgendwie naheliegender das ganze direkt als** string **zu lösen:
static std::string IntToBin(const int input)
{
if(input <= 0)
{
return "";
}
const int rest = input % 2;
const int quotient = input / 2;
return IntToBin(quotient) + (rest ? '1' : '0');
}
static std::string Invert(const std::string input)
{
if(input.empty())
{
return "";
}
const char head = input.front();
const std::string tail = input.substr(1);
return Invert(tail) + head;
}
int main(int argc, char* argv[])
{
for(int i = 1; i < 32; i++)
{
printf("%02d -> %5s -> %5s\n", i, IntToBin(i).c_str(), Invert(IntToBin(i)).c_str());
}
return 0;
}
Wenn Du unbedingt durchgehend mit** int **'s arbeiten willst, die erst ganz zum Schluss als String ausgegeben werden, könnte man das "Umkehren" z.B. so lösen:
static int IntToBin(int input)
{
if(input <= 0)
{
return 0;
}
const int rest = input % 2;
const int quotient = input / 2;
return rest + 10 * IntToBin(quotient);
}
static int Digits(const int input)
{
if(input <= 0)
{
return 0;
}
return 1 + Digits(input / 10);
}
static int Factor(const int input)
{
if(input <= 0)
{
return 1;
}
return 10 * Factor(input - 1);
}
static int Invert(int input)
{
if(input <= 0)
{
return 0;
}
const int head = input % 10;
const int tail = input / 10;
return head * Factor(Digits(tail)) + Invert(tail);
}
int main(int argc, char* argv[])
{
for(int i = 1; i < 32; i++)
{
printf("%2d -> %5d -> %0*d\n", i, IntToBin(i), Digits(IntToBin(i)), Invert(IntToBin(i)));
}
return 0;
}