C# :: Aufgabe #189
9 Lösungen

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
Lösungen:

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; } } }

using System; public class Program { public static void Main() { Console.WriteLine(BinToLong("11010")); } static long BinToLong(string bin) { int maxLength = sizeof(ulong) * 8; if(bin.Length > maxLength) { throw new ArgumentException("String is too long. Current lenght is " + bin.Length + ". Maximum length is " + maxLength); } long longToReturn = 0; for(long bit = 1, i = bin.Length - 1; i > -1; bit <<= 1, i--) { if(bin[(int)i] == '1') { longToReturn |= bit; } else if(bin[(int)i] != '0') { throw new ArgumentException("String is not binary (only 1 and 0)"); } } return longToReturn; } }

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace DualDezimaWandler { public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) { var bin = Convert.ToString(tb1.Text); int Stringlänge = bin.Length; int Rückgabe = 0; if (!System.Text.RegularExpressions.Regex.IsMatch(bin, "[01]{" + Stringlänge + "}") || Stringlänge > 31) throw new Exception("Ungültige Zeichenfolge"); else for (int i = 0; i < Stringlänge; i++){ if (bin[i] == '1') Rückgabe += (int)Math.Pow(2, Stringlänge - 1 - i); } tb2.Text = Convert.ToString(Rückgabe); } } }

<Window x:Class="DualDezimaWandler.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="21*"/> <ColumnDefinition Width="165*"/> <ColumnDefinition Width="310*"/> <ColumnDefinition Width="21*"/> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="47*"/> <RowDefinition Height="31*"/> <RowDefinition Height="30*"/> <RowDefinition Height="30*"/> <RowDefinition Height="24*"/> <RowDefinition Height="39*"/> <RowDefinition Height="119*"/> </Grid.RowDefinitions> <TextBox x:Name="tb1" Grid.Column="1" Grid.Row="1" Grid.ColumnSpan="2"></TextBox> <TextBox x:Name="tb2" Grid.Column="1" Grid.Row="3" Grid.ColumnSpan="2"></TextBox> <Button Grid.Column="1" Grid.Row="5" Click="Button_Click">Umrechnen</Button> </Grid> </Window>

public void BinToDez(string binNo) { var result = 0; for (var i = 0; i < binNo.Length; i++) { result += int.Parse(binNo[binNo.Length - (i + 1)].ToString()) * (int) Math.Pow(2, i); } Console.WriteLine($"Binär : {binNo}"); Console.WriteLine($"Dezimal : {result}"); }

namespace BinärZuDezimal { class Program { static void Main(string[] args) { bool end = false; while (!end) { Console.Clear(); string binary = ""; bool loop = true; while (loop) { Console.WriteLine("Geben Sie eine Binärzahl ein! (Maximal 8 Stellen)"); bool b = false; while (!b) { binary = Console.ReadLine(); if (binary.Length > 8) Console.WriteLine("Die Eingabe ist zu lang!"); else b = true; } int output = 0; try { output = Convert.ToInt32(binary, 2); loop = false; } catch (Exception e) { Console.WriteLine("Sie haben keine Binärzahl eingegeben!"); } } Console.WriteLine("Die von Ihnen eingegebene Binärzahl " + binary + " ergibt Dezimal: " + Convert.ToInt32(binary, 2)); Console.WriteLine("Wollen Sie das Programm beenden? y/n"); if (Console.ReadLine() == "y") end = true; } } } }
Consolen-Programm mit Eingabeschleife um mehrere Strings nacheinander umwandeln/testen zu können.
C#-Code

namespace Csharp_189_BinaryDecimalConverter { using System; using System.Text.RegularExpressions; class Program { static void Main(string[] args) { string inputString; // loop to enter and check several numbers in a row do { Console.Write("Enter binary number or 'Q' to quit: "); inputString = Console.ReadLine(); if (IsValidBinaryNumber(inputString)) { var resultInteger = ConvertBinaryToDecimal(inputString); Console.WriteLine($"Binary={inputString} --> Decimal={resultInteger}\n"); } else { Console.WriteLine("ERROR: Invalid input! \n" + " Allowed characters: '0' and '1'\n" + " Minimum length: 1 character\n" + " Maximum length: 31 characters\n" + " Example input: 100110\n"); } } while (inputString.ToLower() != "q"); } static int ConvertBinaryToDecimal(string binaryString) { var result = 0; var length = binaryString.Length; for(var idx = 0; idx < length; idx++) { // get digits from right to left and convert them to decimal var value = binaryString[length - (idx + 1)] == '1' ? 1 : 0; result += value * (1 << idx); } return result; } static bool IsValidBinaryNumber(string binaryString) { return binaryString.Length < 32 && Regex.IsMatch(binaryString, @"^([01]+)$"); } } }
Ich verstehe nicht, warum niemand zuvor auf diese Lösung kam?
In den Lösungen verkünsteln sich einige, dabei kann das Leben doch so einfach sein... :)
C#-Code
In den Lösungen verkünsteln sich einige, dabei kann das Leben doch so einfach sein... :)

using System; namespace Bin2Dec { class Program { static void Main(string[] args) { try { Console.WriteLine("{0} ist {1}", args[0], Convert.ToInt32(args[0], 2)); } catch(Exception ex) { Console.WriteLine(ex.Message); } Console.ReadKey(); } } }

using System; using System.Collections.Generic; namespace Augfabe_189 { class Program { static void Main(string[] args) { string eingabe = ""; int eingabelänge = 0; int binär = 0; bool wahr = false; eingabe = Eingabe(eingabe); Berechnung(eingabe, wahr, eingabelänge, binär); Console.ReadLine(); } public static void Berechnung(string eingabe, bool wahr, int eingabelänge, int binär) { List<int> listbinär = new List<int>(); double index = -1; double zwischen = 0; if (CheckZahl(eingabe, wahr) == true) { eingabelänge = eingabe.Length; binär = Convert.ToInt32(eingabe); for (int i = 1; i <= eingabelänge; i++) { listbinär.Add(binär % 10); binär /= 10; } Console.WriteLine(); for (int i = 0; i <= listbinär.Count - 1; i++) { double pow = Convert.ToInt32(i); index = listbinär[i] * Math.Pow(2, pow); zwischen = zwischen + index; } Console.WriteLine("Dezimal: "+zwischen); } else { Console.WriteLine("Keine Binaere Zahl eingegeben"); eingabe = Eingabe(eingabe); Berechnung(eingabe, wahr, eingabelänge, binär); } } public static bool CheckZahl(string eingabe, bool wahr) { for (int i = 0; i < eingabe.Length; i++) { if (!(eingabe[i] == '1' || eingabe[i] == '0')) { return wahr = false; } } return wahr = true; } public static string Eingabe(string eingabe) { Console.WriteLine("Binaerzahl eingeben;"); return eingabe = Console.ReadLine(); } } }

using System; using System.Linq; namespace Aufgabe189 { class Program { static void Main(string[] args) { Console.Write("Bitte Dualzahl eingeben: "); string bin = Console.ReadLine(); Console.WriteLine("Binär: " + bin); Console.WriteLine("Dezimal: " + BinToDec(bin)); Console.ReadLine(); } static long BinToDec(string bin) { char[] allowedChars = { '0', '1' }; long retval = 0; for (int i = 0; i < bin.Length ; i++) { char c = bin[bin.Length - 1 - i]; if (!allowedChars.Contains(c)) throw new ArgumentException("Keine gültige Dualzahl", bin); int posval = (int)char.GetNumericValue(c); retval = retval + (int)Math.Pow(2,i)*posval; } return retval; } } }