C# :: Aufgabe #189 :: Lösung #1
9 Lösungen

#189
Zahlen umwandeln: Binär zu Dezimal
Anfänger - C#
von Nachbar
- 13.09.2017 um 14:19 Uhr
Schreibe eine Funktion, die Zahlen aus dem Dualsystem in Zahlen des Dezimalsystems umwandelt.
Beispiel:
Binär: 11010
Dezimal: 26
Beispiel:
Binär: 11010
Dezimal: 26
#1

von hollst (13980 Punkte)
- 15.09.2017 um 11:07 Uhr

using System; using static System.Console; namespace aufgabe_189 { class Program { static void Main() { bool bo_run_again = true; do { string input = string.Empty; bool bo_input_ok = false; while (!bo_input_ok) { input = "Give me an Integer in Binary Representation (eg. 100110): ".LineInfo(); if (!(bo_input_ok = input.Bo_Check_Binarity() && input.Length != 0)) "wrong input".MessageLine(); } (input.CutLeadingZeros() + " (BIN) = " + input.BinToUInt64().ToString() + " (DEZ)").MessageLine(); bo_run_again = !(("press ENTER for repeat or ESC for exit" + Environment.NewLine).KeyInfo().Key == ConsoleKey.Escape); } while (bo_run_again); } } public static class BinToDec { public static void MessageLine(this string s) => WriteLine(s); public static void Message(this string s) => Write(s); public static ConsoleKeyInfo KeyInfo(this string s) { s.Message(); return ReadKey(true); } public static string LineInfo(this string s) { s.Message(); return ReadLine(); } public static bool Bo_Check_Binarity(this string s) { Char[] c = s.ToCharArray(); foreach (Char cc in c) if (!((cc == '0') || (cc == '1'))) return false; return true; } public static string CutLeadingZeros(this string s) { String erg = String.Empty; bool bo_leading_zeros = true; for (var i = 0; i < s.Length; i++) { if (bo_leading_zeros) bo_leading_zeros = s[i] == '0'; if (!bo_leading_zeros) erg += s[i].ToString(); } return erg; } public static ulong BinToUInt64(this string s) { Char[] c = s.CutLeadingZeros().ToCharArray(); ulong pow = 1, erg = 0; for(var i = 0; i < c.Length; i++) { erg += pow * ulong.Parse(c[c.Length - 1 - i].ToString()); pow *= 2; } return erg; } } }
Kommentare:
Für diese Lösung gibt es noch keinen Kommentar
Seite 1 von 0
1