HiveBrain v1.2.0
Get Started
← Back to all entries
snippetcsharpModerate

Function that convert decimal to binary

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
convertdecimalfunctionbinarythat

Problem

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 Conversion(int x)
    {
        var bitConversion = new List();
        var result = x;
        while (result >= 0)
        {
            if (result == 0)
            {
                bitConversion.Add("0");
                break;
            }
            bitConversion.Add((result % 2).ToString(CultureInfo.InvariantCulture));
            result = result / 2;

        }
       bitConversion.Reverse();

       return bitConversion;
    }

Solution

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 Conversion2(int x)
{
   var bitConversion = new List();
   while (x >= 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)

Code Snippets

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

Context

StackExchange Code Review Q#87032, answer score: 19

Revisions (0)

No revisions yet.