0

I'm try to write program can take a decimal number from user by interface form by TextBox tool.. I called it

"txtInput"

then convert it to Binary number and show the result in another TextBox called

"txtOutput"

but I think there's missing something I can't know it because I got this message in "txtOutput"

System.Int32[]

this is my code

        private void BtnConvert_Click(object sender, EventArgs e)
    {
        int [] binNum = new int [32]; //Declartion Array var to store binary number
        int num = int.Parse(txtInput.Text); // Copy input number in num var
        int i = 0; 
        while (num > 0) {
            binNum[i] = num % 2; 
             num/= 2;
            i++;
        }

        //Reverse binNum
        for (int j = i - 1; j >= 0; j--)
        {
            Console.Write(binNum[j]);
            txtOutput.Text = binNum.ToString();
        }
    }

where ever I put txtOutput.Text = binNum.ToString(); inside or outside "for" I got same result.

Haneen
  • 41
  • 5
  • if you arent doing this for school..check out the one liner (https://stackoverflow.com/questions/2954962/convert-integer-to-binary-in-c-sharp)...the professor wouldnt want the one liner – Ctznkane525 Nov 25 '19 at 20:48
  • Side notes: nice trolling title! "decimal" is not "a string representing an integer" but floating point data type used to primarily store money values (1.23), "binary" may mean either just any non-text format as well as "integer in base 2 (binary)", and finally "interface" is `interface` and not UI... – Alexei Levenkov Nov 25 '19 at 20:55

2 Answers2

1

Calling .ToString on an array (or any other object that doesn't override .ToString) will result in a string with the type of the object as its content.

What you want is to concatenate the elements in the array and print those. That can be done e. g. like this:

txtOutput.Text = string.Join("", binNum);

For an array like [1,1,0,1,0] this will output 11010.

Also note that you don't have to reverse the array yourself: you can just call .Reverse on the array (on any IEnumerable<T> actually). So you could write it like this:

txtOutput.Text = string.Join("", binNum.Reverse());
germi
  • 4,628
  • 1
  • 21
  • 38
  • Really thank you for your helping.. I applied this solution and it works good.. thanks again – Haneen Nov 25 '19 at 21:29
  • It's displaying 32 digits together. I want to part them to each 4 digits together, How can I do it ? – Haneen Nov 25 '19 at 21:38
0

C# cannot display arrays directly. The default behaviour of ToString is to display the type name. Many types override ToString to display something more useful, but this is not the case for arrays. You must convert the array to a string yourself

for (int j = i - 1; j >= 0; j--) {
    Console.Write(binNum[j]);
}
string s = String.Join(" ", binNum.Reverse());
txtOutput.Text = s;

Also, don't do that in the for-loop. It needs to be done only once.

Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188