64

What I am looking for is something like PHPs decbin function in C#. That function converts decimals to its representation as a string.

For example, when using decbin(21) it returns 10101 as result.

I found this function which basically does what I want, but maybe there is a better / faster way?

Max
  • 15,693
  • 14
  • 81
  • 131

5 Answers5

165
var result = Convert.ToString(number, 2);

– Almost the only use for the (otherwise useless) Convert class.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
31

Most ways will be better and faster than the function that you found. It's not a very good example on how to do the conversion.

The built in method Convert.ToString(num, base) is an obvious choice, but you can easily write a replacement if you need it to work differently.

This is a simple method where you can specify the length of the binary number:

public static string ToBin(int value, int len) {
   return (len > 1 ? ToBin(value >> 1, len - 1) : null) + "01"[value & 1];
}

It uses recursion, the first part (before the +) calls itself to create the binary representation of the number except for the last digit, and the second part takes care of the last digit.

Example:

Console.WriteLine(ToBin(42, 8));

Output:

00101010
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • Thanks, also very nice option! I already suspected that the function I found was not the best way to do it. – Max Dec 03 '09 at 11:21
  • 2
    +1 for recursion. Although I really don’t like the usage of `null` there, and `""` works just as well. – Konrad Rudolph Dec 03 '09 at 11:23
  • 2
    Although your example is a good illustration, note that this particular function could be implemented more simply and efficiently as: `string s = Convert.ToString(value, 2); return new string('0', len - s.Length) + s;` (assuming the binary number fits in the provided length) – Chiara Coetzee Jan 29 '15 at 05:52
10
int toBase = 2;
string binary = Convert.ToString(21, toBase); // "10101"
Rubens Farias
  • 57,174
  • 8
  • 131
  • 162
5

To have the binary value in (at least) a specified number of digits, padded with zeroes:

string bin = Convert.ToString(1234, 2).PadLeft(16, '0');

The Convert.ToString does the conversion to a binary string.
The PadLeft adds zeroes to fill it up to 16 digits.

Hans Kesting
  • 38,117
  • 9
  • 79
  • 111
0

This is my answer:

    static bool[] Dec2Bin(int value)
    {
        if (value == 0) return new[] { false };
        var n = (int)(Math.Log(value) / Math.Log(2));
        var a = new bool[n + 1];
        for (var i = n; i >= 0; i--)
        {
            n = (int)Math.Pow(2, i);
            if (n > value) continue;
            a[i] = true;
            value -= n;
        }
        Array.Reverse(a);
        return a;
    }

Using Pow instead of modulo and divide so i think it's faster way.

Thinh Vu
  • 476
  • 5
  • 2