Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. c# binary to decimal code -new-

c# binary to decimal code -new-

Scheduled Pinned Locked Moved C#
csharpdata-structureshelp
12 Posts 4 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • M Offline
    M Offline
    mehmetali_06
    wrote on last edited by
    #1

    private void button1_Click(object sender, EventArgs e)
    {
    if (textBox1.Text.Length > 0)
    {
    string sayii = textBox1.Text.Substring(0, textBox1.Text.Length);
    uint[] sayicc = new uint[textBox1.Text.Length];

                for (int i = 0; i < textBox1.Text.Length; i++)
                {
                    sayicc\[i\] = Convert.ToUInt32(sayii\[i\] - 48);
    
                }
    
                uint\[\] dizi2 = new uint\[textBox1.Text.Length\];
                uint bit = 1;
    
                for (int j = 0; j < textBox1.Text.Length; j++)
                {
                    dizi2\[j\] = bit;
                    bit \*= 2;
                }
                Array.Reverse(dizi2);
                uint deger = 0;
                for (int i = 0; i <= dizi2.Length - 1; i++)
                {
                    dizi2\[i\] \*= sayicc\[i\];
    
                    if (sayicc\[i\] == 1)
                    {
                        deger += dizi2\[i\];
                    }
                }
                textBox2.Text = "  " + deger.ToString();
            }
            else
            {
                MessageBox.Show("Deger girilecek alan boş.", "HATA!!!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    
    P Peric ZeljkoP K 3 Replies Last reply
    0
    • M mehmetali_06

      private void button1_Click(object sender, EventArgs e)
      {
      if (textBox1.Text.Length > 0)
      {
      string sayii = textBox1.Text.Substring(0, textBox1.Text.Length);
      uint[] sayicc = new uint[textBox1.Text.Length];

                  for (int i = 0; i < textBox1.Text.Length; i++)
                  {
                      sayicc\[i\] = Convert.ToUInt32(sayii\[i\] - 48);
      
                  }
      
                  uint\[\] dizi2 = new uint\[textBox1.Text.Length\];
                  uint bit = 1;
      
                  for (int j = 0; j < textBox1.Text.Length; j++)
                  {
                      dizi2\[j\] = bit;
                      bit \*= 2;
                  }
                  Array.Reverse(dizi2);
                  uint deger = 0;
                  for (int i = 0; i <= dizi2.Length - 1; i++)
                  {
                      dizi2\[i\] \*= sayicc\[i\];
      
                      if (sayicc\[i\] == 1)
                      {
                          deger += dizi2\[i\];
                      }
                  }
                  textBox2.Text = "  " + deger.ToString();
              }
              else
              {
                  MessageBox.Show("Deger girilecek alan boş.", "HATA!!!", MessageBoxButtons.OK, MessageBoxIcon.Error);
              }
          }
      
      P Offline
      P Offline
      Peter_in_2780
      wrote on last edited by
      #2

      Why not this?

      private void button1_Click(object sender, EventArgs e)
      {
      if (textBox1.Text.Length > 0)
      {
      textBox2.Text = Convert.ToInt32(textBox1.Text, 2).ToString();
      }
      else
      {
      MessageBox.Show("Deger girilecek alan boş.", "HATA!!!", MessageBoxButtons.OK, MessageBoxIcon.Error);
      }
      }

      Peter

      Software rusts. Simon Stephenson, ca 1994.

      M Peric ZeljkoP K 3 Replies Last reply
      0
      • P Peter_in_2780

        Why not this?

        private void button1_Click(object sender, EventArgs e)
        {
        if (textBox1.Text.Length > 0)
        {
        textBox2.Text = Convert.ToInt32(textBox1.Text, 2).ToString();
        }
        else
        {
        MessageBox.Show("Deger girilecek alan boş.", "HATA!!!", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        }

        Peter

        Software rusts. Simon Stephenson, ca 1994.

        M Offline
        M Offline
        mehmetali_06
        wrote on last edited by
        #3

        This code for binary to decimal. I didint see like this easy code. The other calculating codes are too long and complex. I made this and you can use easily.

        1 Reply Last reply
        0
        • P Peter_in_2780

          Why not this?

          private void button1_Click(object sender, EventArgs e)
          {
          if (textBox1.Text.Length > 0)
          {
          textBox2.Text = Convert.ToInt32(textBox1.Text, 2).ToString();
          }
          else
          {
          MessageBox.Show("Deger girilecek alan boş.", "HATA!!!", MessageBoxButtons.OK, MessageBoxIcon.Error);
          }
          }

          Peter

          Software rusts. Simon Stephenson, ca 1994.

          Peric ZeljkoP Offline
          Peric ZeljkoP Offline
          Peric Zeljko
          wrote on last edited by
          #4

          Hello Peter, your code is excelent , but have no control of what user enters, except if it is an emty string, so I shall use your code with small change in that direction.

          void Button1Click(object sender, EventArgs e)
          {
          // TODO: Implement Button1Click

          if (textBox1.Text.Length > 0)
          {
          try 
          {
            textBox2.Text = Convert.ToInt32(textBox1.Text, 2).ToString();
          } 
          catch (Exception) 
          {
            MessageBox.Show("You didn't entered a Binary number !",
          	          "Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
          }
                      
           }
           else
           {
              MessageBox.Show("You didn't entered a Binary number !",
          	         "Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
           }
          

          }

          All the best, Peric Zeljko periczeljkosmederevo@yahoo.com

          P 1 Reply Last reply
          0
          • M mehmetali_06

            private void button1_Click(object sender, EventArgs e)
            {
            if (textBox1.Text.Length > 0)
            {
            string sayii = textBox1.Text.Substring(0, textBox1.Text.Length);
            uint[] sayicc = new uint[textBox1.Text.Length];

                        for (int i = 0; i < textBox1.Text.Length; i++)
                        {
                            sayicc\[i\] = Convert.ToUInt32(sayii\[i\] - 48);
            
                        }
            
                        uint\[\] dizi2 = new uint\[textBox1.Text.Length\];
                        uint bit = 1;
            
                        for (int j = 0; j < textBox1.Text.Length; j++)
                        {
                            dizi2\[j\] = bit;
                            bit \*= 2;
                        }
                        Array.Reverse(dizi2);
                        uint deger = 0;
                        for (int i = 0; i <= dizi2.Length - 1; i++)
                        {
                            dizi2\[i\] \*= sayicc\[i\];
            
                            if (sayicc\[i\] == 1)
                            {
                                deger += dizi2\[i\];
                            }
                        }
                        textBox2.Text = "  " + deger.ToString();
                    }
                    else
                    {
                        MessageBox.Show("Deger girilecek alan boş.", "HATA!!!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            
            Peric ZeljkoP Offline
            Peric ZeljkoP Offline
            Peric Zeljko
            wrote on last edited by
            #5

            Hello mehmetali, peter have excelent solution , I made mine own which is not as elegant. It is console application made in SharpDevelop C#. This code is update of old one, it have no problem with entry of numbers as old version, now it works with float point numbers and it folows full math logic.

            /*
            * Created by SharpDevelop.
            * User: Peric Zeljko
            * Date: 7.10.2011
            * Time: 8:51
            *
            *
            * Simple console program for conversion of
            * Binary numbers to Real numbers
            *
            */
            using System;

            namespace Binary_to_Decimal
            {
            class Program
            {
            public static void Main(string[] args)
            {
            //
            // declaration of variables
            //
            string [] DecimalFloat = new string[2];
            string Binary = "";
            bool RealRelevance = false;
            bool BinaryRelevance = false;
            int Index = 0;
            int Lenght = 0;
            int Exponent = 0;
            int Cipher = 0;
            double BaseExponent = 0;
            double RealNumber = 0;
            double D = 0;
            double F = 0;
            string Negative = "";
            string DecimalPart = "";
            string FloatPart = "";
            string Letter = "";

            		// 
            		// not very desirable but necessary
            		// begining of program label
            		//
            begining :
            			
            		//
            		// Hello message to user
            		//
            		Console.Title = "Program Binary to Real ";
            		Console.SetWindowSize(80,40);
            		Console.ForegroundColor = ConsoleColor.Green;
            		Console.Clear();
            		Console.WriteLine("\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*");
            		Console.WriteLine("                          Binary to Real");
            		Console.WriteLine("\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*");
            		
            		
            		// 
            		// Get number from Console
            		//
            		Console.WriteLine();
            	      Console.Write("Enter binary number (exmpl: 1001) : ");
            	      Binary = "";
            		Binary = Console.ReadLine();
            		Console.WriteLine();
            		Console.WriteLine("\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*");
            
            		
            		// 
            		// Check if it is Real number
            		// 
            		RealRelevance = false;
            		RealNumber = 0;
            		RealRelevance = double.TryParse(Binary,out RealNumber);
            		if (RealRelevance == true)
            		{
            			//
            			// clear sign plus or minus
            			//
            			if (Binary.Contains("-"))
            			{
            				Binary = Binary.TrimStart('-');
            				Negative = "- ";
            				RealNumber = -1 \* RealNumber;
            			}
            			else if (!Binary.Contains("-") && !Binary.Contains("+"))
            			{
            				Negative = "";
            			}
            			else  if (Binary.Contains("+"))
            			{
            				Binary = Bi
            
            1 Reply Last reply
            0
            • Peric ZeljkoP Peric Zeljko

              Hello Peter, your code is excelent , but have no control of what user enters, except if it is an emty string, so I shall use your code with small change in that direction.

              void Button1Click(object sender, EventArgs e)
              {
              // TODO: Implement Button1Click

              if (textBox1.Text.Length > 0)
              {
              try 
              {
                textBox2.Text = Convert.ToInt32(textBox1.Text, 2).ToString();
              } 
              catch (Exception) 
              {
                MessageBox.Show("You didn't entered a Binary number !",
              	          "Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
              }
                          
               }
               else
               {
                  MessageBox.Show("You didn't entered a Binary number !",
              	         "Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
               }
              

              }

              All the best, Peric Zeljko periczeljkosmederevo@yahoo.com

              P Offline
              P Offline
              Peter_in_2780
              wrote on last edited by
              #6

              Indeed your code is better for the real world. My point was about (badly) reinventing the string-to-number conversion. Cheers, Peter

              Software rusts. Simon Stephenson, ca 1994.

              1 Reply Last reply
              0
              • P Peter_in_2780

                Why not this?

                private void button1_Click(object sender, EventArgs e)
                {
                if (textBox1.Text.Length > 0)
                {
                textBox2.Text = Convert.ToInt32(textBox1.Text, 2).ToString();
                }
                else
                {
                MessageBox.Show("Deger girilecek alan boş.", "HATA!!!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                }

                Peter

                Software rusts. Simon Stephenson, ca 1994.

                K Offline
                K Offline
                KP Lee
                wrote on last edited by
                #7

                You know if I saw a piece of code that said binary to decimal, and if I said 1001, I'd expect to get 9 back instead of 1001! You would be in a world of hurt if I entered an 11 digit "binary" number and that is only slightly longer than 1/3 of a 32 bit int.

                P 1 Reply Last reply
                0
                • K KP Lee

                  You know if I saw a piece of code that said binary to decimal, and if I said 1001, I'd expect to get 9 back instead of 1001! You would be in a world of hurt if I entered an 11 digit "binary" number and that is only slightly longer than 1/3 of a 32 bit int.

                  P Offline
                  P Offline
                  Peter_in_2780
                  wrote on last edited by
                  #8

                  If you are saying what I think you are saying, then you need to take a close look at the second argument in the call to Convert.ToInt32(). It wouldn't be me that hurt. Peter

                  Software rusts. Simon Stephenson, ca 1994.

                  K 1 Reply Last reply
                  0
                  • M mehmetali_06

                    private void button1_Click(object sender, EventArgs e)
                    {
                    if (textBox1.Text.Length > 0)
                    {
                    string sayii = textBox1.Text.Substring(0, textBox1.Text.Length);
                    uint[] sayicc = new uint[textBox1.Text.Length];

                                for (int i = 0; i < textBox1.Text.Length; i++)
                                {
                                    sayicc\[i\] = Convert.ToUInt32(sayii\[i\] - 48);
                    
                                }
                    
                                uint\[\] dizi2 = new uint\[textBox1.Text.Length\];
                                uint bit = 1;
                    
                                for (int j = 0; j < textBox1.Text.Length; j++)
                                {
                                    dizi2\[j\] = bit;
                                    bit \*= 2;
                                }
                                Array.Reverse(dizi2);
                                uint deger = 0;
                                for (int i = 0; i <= dizi2.Length - 1; i++)
                                {
                                    dizi2\[i\] \*= sayicc\[i\];
                    
                                    if (sayicc\[i\] == 1)
                                    {
                                        deger += dizi2\[i\];
                                    }
                                }
                                textBox2.Text = "  " + deger.ToString();
                            }
                            else
                            {
                                MessageBox.Show("Deger girilecek alan boş.", "HATA!!!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                    
                    K Offline
                    K Offline
                    KP Lee
                    wrote on last edited by
                    #9

                    Peter's result would put "101" out as " 101" instead of " 5" Sorry, I'm wrong about that. didn't notice or know about the overload. I still like the following logic a little better, it only allows int results, has more error checking, and gives immediate results as you type. (Change your event delegate)

                        private void textBox1\_TextChanged(object sender, EventArgs e)
                        {
                            bool isvalid = true;
                            string txt1="", txt2 = "HATA!!!";
                            string sayii = textBox1.Text;
                            int strt = 0;
                            int bitOffset = 1;
                            byte x;
                            if (sayii.Length == 0)
                            {
                                txt1 = "Deger girilecek alan boş.";
                                isvalid = false;
                            }
                            else if (sayii.Length > 32)
                            {
                                txt1 = "A binary integer can only be 32 bits long";
                                txt2 = "HATA!!!";
                                isvalid = false;
                                MessageBox.Show(txt1, txt2, MessageBoxButtons.OK, MessageBoxIcon.Error);
                                textBox1.Text = sayii.Substring(0, 32);
                                return;// previous command spawns a text changed event
                            }
                            else if (sayii.Length == 32)
                            {
                                x = (byte)sayii\[0\];
                                if (x < 48 || x > 49)
                                {
                                    txt1 = "A binary value must be 1 or 0";
                                    txt2 = "HATA!!!";
                                    isvalid = false;
                                    MessageBox.Show(txt1, txt2, MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    textBox1.Text = sayii.Substring(1, 31);
                                    return;// previous command spawns a text changed event
                                }
                                if (x == 49) strt = int.MinValue;
                                sayii = sayii.Substring(1, 31);
                            }
                            for (int i = sayii.Length; i > 0 && isvalid; )
                            {
                                x = (byte)sayii\[--i\];
                                if (x == 49)
                                    strt += bitOffset;
                                else if (x != 48)
                                {
                                    txt1 = "A binary value must be 1 or 0";
                                    isvalid = false;
                                }
                                bitOffset \*= 2;
                            }
                    
                            if (!isvalid)
                            {
                                MessageBox.Show(txt1, txt2, MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                            else textBox2.Text = "  " + strt.ToString();
                        }
                    
                    P 1 Reply Last reply
                    0
                    • P Peter_in_2780

                      If you are saying what I think you are saying, then you need to take a close look at the second argument in the call to Convert.ToInt32(). It wouldn't be me that hurt. Peter

                      Software rusts. Simon Stephenson, ca 1994.

                      K Offline
                      K Offline
                      KP Lee
                      wrote on last edited by
                      #10

                      True, didn't even notice you were using an overload I didn't know about.

                      1 Reply Last reply
                      0
                      • K KP Lee

                        Peter's result would put "101" out as " 101" instead of " 5" Sorry, I'm wrong about that. didn't notice or know about the overload. I still like the following logic a little better, it only allows int results, has more error checking, and gives immediate results as you type. (Change your event delegate)

                            private void textBox1\_TextChanged(object sender, EventArgs e)
                            {
                                bool isvalid = true;
                                string txt1="", txt2 = "HATA!!!";
                                string sayii = textBox1.Text;
                                int strt = 0;
                                int bitOffset = 1;
                                byte x;
                                if (sayii.Length == 0)
                                {
                                    txt1 = "Deger girilecek alan boş.";
                                    isvalid = false;
                                }
                                else if (sayii.Length > 32)
                                {
                                    txt1 = "A binary integer can only be 32 bits long";
                                    txt2 = "HATA!!!";
                                    isvalid = false;
                                    MessageBox.Show(txt1, txt2, MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    textBox1.Text = sayii.Substring(0, 32);
                                    return;// previous command spawns a text changed event
                                }
                                else if (sayii.Length == 32)
                                {
                                    x = (byte)sayii\[0\];
                                    if (x < 48 || x > 49)
                                    {
                                        txt1 = "A binary value must be 1 or 0";
                                        txt2 = "HATA!!!";
                                        isvalid = false;
                                        MessageBox.Show(txt1, txt2, MessageBoxButtons.OK, MessageBoxIcon.Error);
                                        textBox1.Text = sayii.Substring(1, 31);
                                        return;// previous command spawns a text changed event
                                    }
                                    if (x == 49) strt = int.MinValue;
                                    sayii = sayii.Substring(1, 31);
                                }
                                for (int i = sayii.Length; i > 0 && isvalid; )
                                {
                                    x = (byte)sayii\[--i\];
                                    if (x == 49)
                                        strt += bitOffset;
                                    else if (x != 48)
                                    {
                                        txt1 = "A binary value must be 1 or 0";
                                        isvalid = false;
                                    }
                                    bitOffset \*= 2;
                                }
                        
                                if (!isvalid)
                                {
                                    MessageBox.Show(txt1, txt2, MessageBoxButtons.OK, MessageBoxIcon.Error);
                                }
                                else textBox2.Text = "  " + strt.ToString();
                            }
                        
                        P Offline
                        P Offline
                        Peter_in_2780
                        wrote on last edited by
                        #11

                        See this reply[^] above. The same comment applies here. Also, have a look at this thread[^]. Peter

                        Software rusts. Simon Stephenson, ca 1994.

                        K 1 Reply Last reply
                        0
                        • P Peter_in_2780

                          See this reply[^] above. The same comment applies here. Also, have a look at this thread[^]. Peter

                          Software rusts. Simon Stephenson, ca 1994.

                          K Offline
                          K Offline
                          KP Lee
                          wrote on last edited by
                          #12

                          Peter_in_2780 wrote:

                          Also, have a look at this thread[^].

                          "this thread" got me here in the first place. :) I know this is inefficient, but as a learning tool, this makes a good example of how signed integers work. (and maybe even let him learn how to code a little more efficiently.) I think his original example would say "1xyz1" was 33. (I don't remember his original code exactly, so I'm going from what I remember thinking of it.) I actually learned something. My version has a bug in it. My "bit *= 2;" (my expectation and I forgot what I used for "bit") should have blown up when I tried to make it 2^32 power, instead it made it -2^31 (int.MinValue). To fix my bug, add "if (i > 0) " before that statement and take out the prior "if ...Length == 32" logic.

                          1 Reply Last reply
                          0
                          Reply
                          • Reply as topic
                          Log in to reply
                          • Oldest to Newest
                          • Newest to Oldest
                          • Most Votes


                          • Login

                          • Don't have an account? Register

                          • Login or register to search.
                          • First post
                            Last post
                          0
                          • Categories
                          • Recent
                          • Tags
                          • Popular
                          • World
                          • Users
                          • Groups