C# :: Aufgabe #337 :: Lösung #1
2 Lösungen
#337
Zahlensysteme konvertieren
Anfänger - C#
von JKooP
- 01.11.2020 um 10:53 Uhr
Schreibe eine Methode/Funktion, mit der man jede als Datentyp „String“ angegeben Zahl eines beliebigen Zahlensystems (binär, ternär, oktal, hexadezimal…) ins Dezimalsystem konvertieren kann.
Beispiele:
("1010", 2) binär --> 10 dezimal
("120", 3) ternär --> 15 dezimal
("15", 8) oktal --> 13 dezimal
("FF", 16) hexadezimal --> 255 dezimal
Viel Spaß
Beispiele:
("1010", 2) binär --> 10 dezimal
("120", 3) ternär --> 15 dezimal
("15", 8) oktal --> 13 dezimal
("FF", 16) hexadezimal --> 255 dezimal
Viel Spaß
#1
von MarkusH. (440 Punkte)
- 16.11.2020 um 18:53 Uhr
using System;
using System.Collections.Generic;
namespace _337___Zahlensysteme_konvertieren
{
class Program
{
private static Dictionary<char, int> charNumberRelationships;
private static int[] decimalBaseInputArray;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Nicht verwendete Parameter entfernen", Justification = "<Ausstehend>")]
static void Main(string[] args)
{
FillDictionary();
Console.BackgroundColor = ConsoleColor.Blue;
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("************************************************************");
Console.WriteLine("** **");
Console.WriteLine("** Zahlensysteme in das Dezimalsystem konvertieren **");
Console.WriteLine("** **");
Console.WriteLine("************************************************************");
Console.WriteLine("** Unterstützt werden die Zahlensysteme von **");
Console.WriteLine("** Basis 2 bis Basis 16. **");
Console.WriteLine("** Zum Beenden des Programms das Eingabefeld leer lassen! **");
Console.WriteLine("************************************************************");
Console.WriteLine("** **");
while (true)
{
Console.Write("Geben Sie die zu konvertierende Zahl ein: ");
string userInputValue = Console.ReadLine();
if (string.IsNullOrEmpty(userInputValue)) break;
Console.Write("Geben Sie das Zahlensystem an: ");
string userInputNumberBase = Console.ReadLine();
if (TryConvertAnyNumericBaseToDecimalBase(Convert.ToInt32(userInputNumberBase), userInputValue.Trim().ToUpper(), out string result))
{
Console.WriteLine($"Der Wert { userInputValue } im Zahlensystem { userInputNumberBase } entspricht dem Wert { result } im Dezimalsystem.");
}
Console.WriteLine("************************************************************");
}
}
/// <summary>
/// Try to convert a given input value and number system to its decimal equivalent
/// </summary>
/// <param name="inputBase">The input number system</param>
/// <param name="input">The input value</param>
/// <param name="result">The calculated result</param>
/// <returns>True if the conversion is successful, otherwise false</returns>
private static bool TryConvertAnyNumericBaseToDecimalBase(int inputBase, string input, out string result)
{
result = "0";
if (input.Equals("0")) return true;
if (inputBase < 2 || inputBase > 16)
{
Console.WriteLine("Ungültiges Zahlensystem!");
return false;
}
char[] reversedInputArray = ReverseArray(input);
if (CheckinputString(inputBase, reversedInputArray))
{
if (decimalBaseInputArray != null && decimalBaseInputArray.Length > 0)
{
result = CalculateDecimalSum(inputBase).ToString();
}
else
{
Console.WriteLine("Ein Fehler ist aufgetreten!");
return false;
}
}
else
{
Console.WriteLine("Ein Fehler ist aufgetreten!");
return false;
}
return true;
}
/// <summary>
/// Calculate the decimal value of the input value
/// using the Horner method
/// </summary>
/// <param name="inputBase">The input number base</param>
/// <returns>The decimal value of the input value</returns>
private static double CalculateDecimalSum(int inputBase)
{
double sum = 0;
for (int i = 0; i < decimalBaseInputArray.Length; i++)
{
sum += decimalBaseInputArray[i] * Math.Pow(inputBase, i);
}
return sum;
}
/// <summary>
/// Reverse an array
/// </summary>
/// <param name="input">The array to reverse</param>
/// <returns>The reversed array</returns>
private static char[] ReverseArray(string input)
{
char[] reversedInputArray = input.ToCharArray();
Array.Reverse(reversedInputArray);
return reversedInputArray;
}
/// <summary>
/// Check the input value for invalid characters.
/// Examples:
/// Binary: Only 0 and 1 are valid
/// Octal: Only the values from 0 to 7 are valid
/// Duodecimal: Only the values from 0 to 9, A and B are valid
/// </summary>
/// <param name="inputBase">The inbut number system</param>
/// <param name="inputArray">The input value in char array representation</param>
/// <returns>True if the check is successful, otherwise false</returns>
private static bool CheckinputString(int inputBase, char[] inputArray)
{
bool isValid = true;
decimalBaseInputArray = new int[inputArray.Length];
int index = -1;
foreach (char inputChar in inputArray)
{
index++;
if(charNumberRelationships.ContainsKey(inputChar))
{
int number = charNumberRelationships[inputChar];
if(number >= inputBase)
{
Console.WriteLine($"{ inputChar } ist ein ungültiger Wert im Zahlensystem mit der Basis { inputBase }!");
isValid = false;
decimalBaseInputArray = null;
break;
}
else
{
decimalBaseInputArray[index] = number;
}
}
else
{
Console.WriteLine($"{ inputChar } ist ungültig!");
isValid = false;
decimalBaseInputArray = null;
break;
}
}
return isValid;
}
/// <summary>
/// Fill the dictionary with valid chars
/// </summary>
private static void FillDictionary()
{
charNumberRelationships = new Dictionary<char, int>
{
{ '0', 0 },
{ '1', 1 },
{ '2', 2 },
{ '3', 3 },
{ '4', 4 },
{ '5', 5 },
{ '6', 6 },
{ '7', 7 },
{ '8', 8 },
{ '9', 9 },
{ 'A', 10 },
{ 'B', 11 },
{ 'C', 12 },
{ 'D', 13 },
{ 'E', 14 },
{ 'F', 15 }
};
}
}
}
Kommentare:
Für diese Lösung gibt es noch keinen Kommentar
Seite 1 von 0
1
