Conversion of an integer to a binary string

ddanbe 1 Tallied Votes 269 Views Share

I you ever would have the need to do this conversion you probably would use
string myStr = Convert.ToString(myInt,2); which does the job.
Here is presented another way to do this with some simple formatting included.
Some highlights for newbies and not so newbies:
Line 9: Custom enum type
Line 37: const calculation
Line 42: Reversed for loop from up to down (to avoid having to reverse the array of bits afterwards)
Line 45: Use of left shift operator
Line 48: Use of ternary operator as a parameter to a method
Line 68: Use of LINQ (explained in the code) I like LINQ!
Line 70: String Join method

Hope you like it. As always, awaiting your comments and remarks!

Teme64 commented: Very handy snippet +11
using System;
using System.Linq;
using System.Text;

namespace ConsoleInterfaces
    enum FormatOptions

    class Program 
        static void Main(string[] args)
            Console.WriteLine("CONVERSION TO BINARY OF SOME INTEGERS.");
            Console.WriteLine("Different formats used.");
            Console.WriteLine("-10 is: {0}", convertToBits(-10, FormatOptions.separateNibbles));
            Console.WriteLine("1234 is: {0}", convertToBits(1234, FormatOptions.separateBytes));
            Console.WriteLine("12345678 is: {0}", convertToBits(12345678, FormatOptions.none));
            Console.WriteLine("Standard conversion of 1234:");
            var result = Convert.ToString(1234, 2);

        static public string convertToBits(int num, FormatOptions Options)
            const int nibbleSize = 4;
            const int byteSize = 8;
            const int bitMask = 1;
            const int intSize = sizeof(int) * byteSize;

            StringBuilder bitStr = new StringBuilder();
            int bit = 0;

            for (int pos = intSize - 1; pos >= 0 ; pos--)
                // Shift right, number of positions, and AND with num                   
                bit = num & (bitMask << pos);

                // Append a char to bitStr depending on whether bit true=1 or false=0
                bitStr.Append(bit == 0 ? '0' : '1');               
            switch (Options)
                case FormatOptions.separateNibbles:
                    return splitInsert(bitStr.ToString(), nibbleSize, " | ");
                case FormatOptions.separateBytes:
                    return splitInsert(bitStr.ToString(), byteSize, " ");
                case FormatOptions.trimLeadingZeros:
                    return bitStr.ToString().TrimStart('0');
                default: // = FormatOptions.none
            return bitStr.ToString();

        // split a string in smaller groups, insert a string between
        // each group and concatenate.
        static public string splitInsert(string str, int splitWidth, string insertStr)
            var results = str.Select((ch, i) => new { ch, i })
                                .GroupBy(x => x.i / splitWidth)
                                .Select(gr => String.Concat(gr.Select(y =>;
            return String.Join(insertStr, results);
        // LINQ *********************************************************************
        // results will be an Enumerable collection of strings
        // out of the string of zeros and ones from bitStr, we select new anonymous objects
        // consisting of a char and an index ( new { ch, i})
        // next, we group those objects according to splitWidth and index
        // eg. if splitWidth is 4 the first group will consist of objects with index 0,1,2 and 3
        // the second group will consist of objects with index 4,5,6 and 7 and so on.
        // and lastly we select each char in each group and concatenate the chars together