0

I am newbie in C#, however I have tried to write code for converting Decimal to binary, i know there are a lot other ways and probably a lot easier ways, but i just wanted to try it this way - with List. Can someone please tell me what I`m doing wrong ? Thanks!

static void Main(string[] args)
{
    long decimalNum = long.Parse(Console.ReadLine());
    long divideNumber = decimalNum;
    List<string> BinaryResult = new List<string>();

    for (int i = 0; divideNumber == 0; i++)
    {
        long divideBytwo = divideNumber % 2;

        if (divideBytwo == 1)
        {
            BinaryResult.Add("1");
        }

        if (divideBytwo == 0)
        {
            BinaryResult.Add("0");
        }


        divideNumber /= 2;
    }

    for (int i = 0; i < BinaryResult.Count; i++)
    {
        Console.Write(BinaryResult[BinaryResult.Count - i]);
    }
}

Is there a way with integer list too or .. Am I completely wrong ?

Jackie
  • 327
  • 2
  • 13
  • 1
    Why do you think you're doing something wrong? Is something not working? Please edit the question providing all necessary information, especially what happens, what should happen and possible errors. – Sami Kuhmonen Jun 27 '15 at 15:06

3 Answers3

2

Just use this if converting a number to binary is all you want:

int value = 8;
string binary = Convert.ToString(value, 2);
Bogdan Banciu
  • 169
  • 1
  • 6
0

A few things:

  1. In your first for loop, divideNumber == 0 is the opposite of what you want: it says that you want the loop to run as long as divideNumber is zero, whereas what you really want is for the loop to run until divideNumber is zero. Try divideNumber != 0 instead.

  2. In your second for loop, if BinaryResult contains any data, you're going to get an out-of-bounds exception. You're trying to read indexes 1 through x (where x is the number of items in the list) whereas the valid indexes are 0 through x - 1. You can either fix your indexes, or since you're accessing the elements in the opposite order in which you created them, you might find it more intuitive to use a Stack<T> instead of a List<T>.

Joe Farrell
  • 3,502
  • 1
  • 15
  • 25
0

A possible solution might be with using Stack as suggested by @Joe. I also used string builder instead of using List of strings. Keep in mind I'm also learning C#, so my answer probably isn't the best possible.

static void Main(string[] args)
{   
    long decimalNum = long.Parse(Console.ReadLine());
    StringBuilder sb = new StringBuilder();

    Stack<String> BinaryResult = new Stack<string>();

    while (decimalNum > 0)
    {
        var rem = decimalNum%2;
        BinaryResult.Push(rem.ToString());
        decimalNum = decimalNum/2;
    }

    while (BinaryResult.Count > 0)
    {
        sb.Append(BinaryResult.Pop().ToString());
    }

    Console.WriteLine(sb.ToString());
    Console.ReadLine();
}
Asunez
  • 2,327
  • 1
  • 23
  • 46