C# :: Aufgabe #189

3 Lösungen Lösungen öffentlich

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

Lösungen:

vote_ok
von hollst (6850 Punkte) - 15.09.2017 um 11:07 Uhr
Quellcode ausblenden C#-Code
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;
        }
    }
}
vote_ok
von DBqFetti (2150 Punkte) - 15.09.2017 um 22:57 Uhr
Quellcode ausblenden C#-Code
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;
  }
}
vote_ok
von Layn (40 Punkte) - 20.09.2017 um 13:49 Uhr
Quellcode ausblenden C#-Code
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);

        }

        
    }
}




Quellcode ausblenden XML-Code
<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>