Function that convert decimal to binary I have a function that converts an integer to its binary representation. I am wondering if there is any way I can improve the function.

 public List&lt;string&gt; Conversion(int x)
    {
        var bitConversion = new List&lt;string&gt;();
        var result = x;
        while (result &gt;= 0)
        {
            if (result == 0)
            {
                bitConversion.Add("0");
                break;
            }
            bitConversion.Add((result % 2).ToString(CultureInfo.InvariantCulture));
            result = result / 2;

        }
       bitConversion.Reverse();

       return bitConversion;
    }
One major improvement would be to just use what is supplied through .NET:

Convert.ToString(int, 2);


where int is your supplied argument.

Convert.ToString Method (Int32, Int32)


  Converts the value of a 32-bit signed integer to its equivalent string representation in a specified base.


Note that this returns you a string value like 10000110100001, which is the representation of a binary number. In your code you store them as string representations and in separate entries in your collection, which is not the way a number should be stored. It's like creating an array with values "1" and "2" to represent the number 12.

If this is your intention then you can always work towards that of course but it might be an indication that something else is wrong for needing it like that.



However if you want to stay with your own implementation, there are a few things you could change around:

public List&lt;string&gt; Conversion2(int x)
{
   var bitConversion = new List&lt;string&gt;();
   while (x &gt;= 0)
   {
       if (x == 0)
       {
           bitConversion.Add("0");
           break;
       }
       bitConversion.Add((x % 2).ToString(CultureInfo.InvariantCulture));
       x /=  2;
   }
  bitConversion.Reverse();
  return bitConversion;
}



Remove the unnecessary result variable
Contract x = x / 2 to x /= 2 (compound assignment operator)