264

How to convert an integer number into its binary representation?

I'm using this code:

String input = "8";
String output = Convert.ToInt32(input, 2).ToString();

But it throws an exception:

Could not find any parsable digits

3
  • 1
    Are you trying to convert the string representation of a number, or an actual number? And are you trying to convert to decimal, or int? Your example doesn't really match your question.
    – womp
    Jun 2, 2010 at 4:18
  • If you're looking to convert decimal to bytes, you can use this code: gist.github.com/eranbetzalel/… Apr 14, 2013 at 20:14
  • 2
    You're trying to parse a base-10 string as base-2. That's why the call fails. Jul 22, 2019 at 17:08

22 Answers 22

520

Your example has an integer expressed as a string. Let's say your integer was actually an integer, and you want to take the integer and convert it to a binary string.

int value = 8;
string binary = Convert.ToString(value, 2);

Which returns 1000.

4
  • 1
    is there any similar method to convert binary to decimal?
    – kashif
    Jan 24, 2013 at 8:26
  • 52
    @kashif int value = Convert.ToInt32("1101", 2) would give value the value 13.
    – flindeberg
    Mar 5, 2013 at 18:20
  • How does this work? is the "2" the base and will work for any base?
    – Xonatron
    May 22, 2021 at 19:25
  • 2
    @Xonatron: learn.microsoft.com/en-us/dotnet/api/… May 23, 2021 at 4:10
60

Convert from any classic base to any base in C#

string number = "100";
int fromBase = 16;
int toBase = 10;

string result = Convert.ToString(Convert.ToInt32(number, fromBase), toBase);

// result == "256"

Supported bases are 2, 8, 10 and 16

2
  • 1
    This will not work. I simply tried string binary = Convert.ToString(533, 26); and got a ArgumentException: Invalid base
    – Magnum
    Apr 25, 2014 at 18:09
  • 8
    Yep, from MSDN: only classic bases are supported msdn.microsoft.com/en-us/library/8s62fh68(v=vs.110).aspx toBase Type: System.Int32 The base of the return value, which must be 2, 8, 10, or 16.
    – sritmak
    Apr 30, 2014 at 8:12
41

Very Simple with no extra code, just input, conversion and output.

using System;

namespace _01.Decimal_to_Binary
{
    class DecimalToBinary
    {
        static void Main(string[] args)
        {
            Console.Write("Decimal: ");
            int decimalNumber = int.Parse(Console.ReadLine());

            int remainder;
            string result = string.Empty;
            while (decimalNumber > 0)
            {
                remainder = decimalNumber % 2;
                decimalNumber /= 2;
                result = remainder.ToString() + result;
            }
            Console.WriteLine("Binary:  {0}",result);
        }
    }
}
2
  • 1
    For a generic alphabet, this should be do{ [...] }while(decimalNumber > 0); Mar 4, 2015 at 15:51
  • In case of decimalNumber = 0, result is Empty. Please update to while (decimalNumber > 0 || string.IsNullOrEmpty(result))
    – akkapolk
    Sep 23, 2019 at 7:30
15

http://zamirsblog.blogspot.com/2011/10/convert-decimal-to-binary-in-c.html

    public string DecimalToBinary(string data)
    {
        string result = string.Empty;
        int rem = 0;
        try
        {
            if (!IsNumeric(data))
                error = "Invalid Value - This is not a numeric value";
            else
            {
                int num = int.Parse(data);
                while (num > 0)
                {
                    rem = num % 2;
                    num = num / 2;
                    result = rem.ToString() + result;
                }
            }
        }
        catch (Exception ex)
        {
            error = ex.Message;
        }
        return result;
    }
2
  • 2
    Not sure how this differs from Xenon's answer. Nov 8, 2012 at 17:22
  • 6
    He answered this before Xenon May 28, 2016 at 19:06
12

primitive way:

public string ToBinary(int n)
{
    if (n < 2) return n.ToString();

    var divisor = n / 2;
    var remainder = n % 2;

    return ToBinary(divisor) + remainder;
}
2
  • 3
    Fails with negatives, but I upvoted anyway because it's a fun answer. Aug 9, 2020 at 10:36
  • appreciated yr feedback @BrainSlugs83
    – Daniel B
    Aug 9, 2020 at 19:13
9

Another alternative but also inline solution using Enumerable and LINQ is:

int number = 25;
    
string binary = Enumerable.Range(0, (int)Math.Log(number, 2) + 1).Aggregate(string.Empty, (collected, bitshifts) => ((number >> bitshifts) & 1 ) + collected);
4
  • 1
    After trying many (but not all) of the non-BCL answers here, this is the first answer I found that actually works. Most of them fail spectacularly.
    – InteXX
    Sep 20, 2019 at 14:34
  • 1
    thank you for discovering my code :) but as you see, it's joke from performance point of view Sep 21, 2019 at 19:28
  • Well, we can't have everything, can we? ;-)
    – InteXX
    Sep 21, 2019 at 23:50
  • 1
    This answer legit made me laugh. Here have an up vote, you deserve it. Aug 9, 2020 at 10:33
8

Convert.ToInt32(string, base) does not do base conversion into your base. It assumes that the string contains a valid number in the indicated base, and converts to base 10.

So you're getting an error because "8" is not a valid digit in base 2.

String str = "1111";
String Ans = Convert.ToInt32(str, 2).ToString();

Will show 15 (1111 base 2 = 15 base 10)

String str = "f000";
String Ans = Convert.ToInt32(str, 16).ToString();

Will show 61440.

6
    static void convertToBinary(int n)
    {
        Stack<int> stack = new Stack<int>();
        stack.Push(n);
        // step 1 : Push the element on the stack
        while (n > 1)
        {
            n = n / 2;
            stack.Push(n);
        }

        // step 2 : Pop the element and print the value
        foreach(var val in stack)
        {
            Console.Write(val % 2);
        }
     }
2
  • 1
    Hello ! You should add some comments with the code you posted :)
    – toshiro92
    Mar 19, 2019 at 21:40
  • 1
    This function will convert integer to binary in C#. To convert integer to Binary, we repeatedly divide the quotient by the base, until the quotient is zero, making note of the remainders at each step (used Stack.Push to store the values). Then, we write the remainders in reverse, starting at the bottom and appending to the right each time (loop thru the stack to print the values). Mar 20, 2019 at 17:21
4

I know this answer would look similar to most of the answers already here, but I noticed just about none of them uses a for-loop. This code works, and can be considered simple, in the sense it will work without any special functions, like a ToString() with parameters, and is not too long as well. Maybe some prefer for-loops instead of just while-loop, this may be suitable for them.

public static string ByteConvert (int num)
{
    int[] p = new int[8];
    string pa = "";
    for (int ii = 0; ii<= 7;ii = ii +1)
    {
        p[7-ii] = num%2;
        num = num/2;
    }
    for (int ii = 0;ii <= 7; ii = ii + 1)
    {
        pa += p[ii].ToString();
    }
    return pa;
}
4
using System;

class Program 
{
    static void Main(string[] args) {

        try {

            int i = (int) Convert.ToInt64(args[0]);
            Console.WriteLine("\n{0} converted to Binary is {1}\n", i, ToBinary(i));

        } catch(Exception e) {
            Console.WriteLine("\n{0}\n", e.Message);
        }
    }

    public static string ToBinary(Int64 Decimal) {
        // Declare a few variables we're going to need
        Int64 BinaryHolder;
        char[] BinaryArray;
        string BinaryResult = "";

        while (Decimal > 0) {
            BinaryHolder = Decimal % 2;
            BinaryResult += BinaryHolder;
            Decimal = Decimal / 2;
        }

        BinaryArray = BinaryResult.ToCharArray();
        Array.Reverse(BinaryArray);
        BinaryResult = new string(BinaryArray);

        return BinaryResult;
    }
}
1
  • 11
    You're reinventing the wheel here. The BCL already contains methods to do this.
    – Eltariel
    Jun 2, 2010 at 6:37
3

This function will convert integer to binary in C#:

public static string ToBinary(int N)
{
    int d = N;
    int q = -1;
    int r = -1;

    string binNumber = string.Empty;
    while (q != 1)
    {
        r = d % 2;
        q = d / 2;
        d = q;
        binNumber = r.ToString() + binNumber;
    }
    binNumber = q.ToString() + binNumber;
    return binNumber;
}
2
  • 3
    You should explain how your code answers the question. Please read SO guidelines before posting.
    – sparkitny
    Jan 17, 2018 at 10:39
  • The above written code converts unsigned integer number into its binary string.
    – Govind
    Jan 17, 2018 at 11:08
3
class Program
{
    static void Main(string[] args)
    {
        var @decimal = 42;
        var binaryVal = ToBinary(@decimal, 2);

        var binary = "101010";
        var decimalVal = ToDecimal(binary, 2);

        Console.WriteLine("Binary value of decimal {0} is '{1}'", @decimal, binaryVal);
        Console.WriteLine("Decimal value of binary '{0}' is {1}", binary, decimalVal);
        Console.WriteLine();

        @decimal = 6;
        binaryVal = ToBinary(@decimal, 3);

        binary = "20";
        decimalVal = ToDecimal(binary, 3);

        Console.WriteLine("Base3 value of decimal {0} is '{1}'", @decimal, binaryVal);
        Console.WriteLine("Decimal value of base3 '{0}' is {1}", binary, decimalVal);
        Console.WriteLine();


        @decimal = 47;
        binaryVal = ToBinary(@decimal, 4);

        binary = "233";
        decimalVal = ToDecimal(binary, 4);

        Console.WriteLine("Base4 value of decimal {0} is '{1}'", @decimal, binaryVal);
        Console.WriteLine("Decimal value of base4 '{0}' is {1}", binary, decimalVal);
        Console.WriteLine();

        @decimal = 99;
        binaryVal = ToBinary(@decimal, 5);

        binary = "344";
        decimalVal = ToDecimal(binary, 5);

        Console.WriteLine("Base5 value of decimal {0} is '{1}'", @decimal, binaryVal);
        Console.WriteLine("Decimal value of base5 '{0}' is {1}", binary, decimalVal);
        Console.WriteLine();

        Console.WriteLine("And so forth.. excluding after base 10 (decimal) though :)");
        Console.WriteLine();


        @decimal = 16;
        binaryVal = ToBinary(@decimal, 11);

        binary = "b";
        decimalVal = ToDecimal(binary, 11);

        Console.WriteLine("Hexidecimal value of decimal {0} is '{1}'", @decimal, binaryVal);
        Console.WriteLine("Decimal value of Hexidecimal '{0}' is {1}", binary, decimalVal);
        Console.WriteLine();
        Console.WriteLine("Uh oh.. this aint right :( ... but let's cheat :P");
        Console.WriteLine();

        @decimal = 11;
        binaryVal = Convert.ToString(@decimal, 16);

        binary = "b";
        decimalVal = Convert.ToInt32(binary, 16);

        Console.WriteLine("Hexidecimal value of decimal {0} is '{1}'", @decimal, binaryVal);
        Console.WriteLine("Decimal value of Hexidecimal '{0}' is {1}", binary, decimalVal);

        Console.ReadLine();
    }


    static string ToBinary(decimal number, int @base)
    {
        var round = 0;
        var reverseBinary = string.Empty;

        while (number > 0)
        {
            var remainder = number % @base;
            reverseBinary += remainder;

            round = (int)(number / @base);
            number = round;
        }

        var binaryArray = reverseBinary.ToCharArray();
        Array.Reverse(binaryArray);

        var binary = new string(binaryArray);
        return binary;
    }

    static double ToDecimal(string binary, int @base)
    {
        var val = 0d;

        if (!binary.All(char.IsNumber))
            return 0d;

        for (int i = 0; i < binary.Length; i++)
        {
            var @char = Convert.ToDouble(binary[i].ToString());

            var pow = (binary.Length - 1) - i;
            val += Math.Pow(@base, pow) * @char;
        }

        return val;
    }
}

Learning sources:

Everything you need to know about binary

including algorithm to convert decimal to binary

1
  • Thanks for demonstrating ToDecimal() method as well.
    – Rajiv
    Jun 17, 2017 at 8:13
2
class Program{

   static void Main(string[] args){

      try{

     int i = (int)Convert.ToInt64(args[0]);
         Console.WriteLine("\n{0} converted to Binary is {1}\n",i,ToBinary(i));

      }catch(Exception e){

         Console.WriteLine("\n{0}\n",e.Message);

      }

   }//end Main


        public static string ToBinary(Int64 Decimal)
        {
            // Declare a few variables we're going to need
            Int64 BinaryHolder;
            char[] BinaryArray;
            string BinaryResult = "";

            while (Decimal > 0)
            {
                BinaryHolder = Decimal % 2;
                BinaryResult += BinaryHolder;
                Decimal = Decimal / 2;
            }

            // The algoritm gives us the binary number in reverse order (mirrored)
            // We store it in an array so that we can reverse it back to normal
            BinaryArray = BinaryResult.ToCharArray();
            Array.Reverse(BinaryArray);
            BinaryResult = new string(BinaryArray);

            return BinaryResult;
        }


}//end class Program
2

BCL provided Convert.ToString(n, 2) is good, but in case you need an alternate implementation which is few ticks faster than BCL provided one.

Following custom implementation works for all integers(-ve and +ve). Original source taken from https://davidsekar.com/algorithms/csharp-program-to-convert-decimal-to-binary

static string ToBinary(int n)
{
    int j = 0;
    char[] output = new char[32];

    if (n == 0)
        output[j++] = '0';
    else
    {
        int checkBit = 1 << 30;
        bool skipInitialZeros = true;
        // Check the sign bit separately, as 1<<31 will cause
        // +ve integer overflow
        if ((n & int.MinValue) == int.MinValue)
        {
            output[j++] = '1';
            skipInitialZeros = false;
        }

        for (int i = 0; i < 31; i++, checkBit >>= 1)
        {
            if ((n & checkBit) == 0)
            {
                if (skipInitialZeros)
                    continue;
                else
                    output[j++] = '0';
            }
            else
            {
                skipInitialZeros = false;
                output[j++] = '1';
            }
        }
    }

    return new string(output, 0, j);
}

Above code is my implementation. So, I'm eager to hear any feedback :)

1
    // I use this function
    public static string ToBinary(long number)
    {
        string digit = Convert.ToString(number % 2);
        if (number >= 2)
        {
            long remaining = number / 2;
            string remainingString = ToBinary(remaining);
            return remainingString + digit;
        }
        return digit;
     }
1
        static void Main(string[] args) 
        {
        Console.WriteLine("Enter number for converting to binary numerical system!");
        int num = Convert.ToInt32(Console.ReadLine());
        int[] arr = new int[16];

        //for positive integers
        if (num > 0)
        {

            for (int i = 0; i < 16; i++)
            {
                if (num > 0)
                {
                    if ((num % 2) == 0)
                    {
                        num = num / 2;
                        arr[16 - (i + 1)] = 0;
                    }
                    else if ((num % 2) != 0)
                    {
                        num = num / 2;
                        arr[16 - (i + 1)] = 1;
                    }
                }
            }
            for (int y = 0; y < 16; y++)
            {
                Console.Write(arr[y]);
            }
            Console.ReadLine();
        }

        //for negative integers
        else if (num < 0)
        {
            num = (num + 1) * -1;

            for (int i = 0; i < 16; i++)
            {
                if (num > 0)
                {
                    if ((num % 2) == 0)
                    {
                        num = num / 2;
                        arr[16 - (i + 1)] = 0;
                    }
                    else if ((num % 2) != 0)
                    {
                        num = num / 2;
                        arr[16 - (i + 1)] = 1;
                    }
                }
            }

            for (int y = 0; y < 16; y++)
            {
                if (arr[y] != 0)
                {
                    arr[y] = 0;
                }
                else
                {
                    arr[y] = 1;
                }
                Console.Write(arr[y]);
            }
            Console.ReadLine();
        }           
    }
3
  • 1
    I know that the code is pretty basic and not too simple but working also with negative numbers Mar 23, 2017 at 15:37
  • You are receiving 32 bit integer, but your output array is of size - 16 bits. Just saying... Nov 19, 2017 at 21:36
  • 1
    Yes, the remark is correct. It is right to use short for this code, but it works with int aswell. The example is with small numbers. If we want to use large numbers, the types must be changed. The idea is that if we want to work with negative numbers, the result should be at least one byte bigger so the program can see that this is an inverted additional code. Nov 21, 2017 at 12:48
1

This might be helpful if you want a concise function that you can call from your main method, inside your class. You may still need to call int.Parse(toBinary(someint)) if you require a number instead of a string but I find this method work pretty well. Additionally, this can be adjusted to use a for loop instead of a do-while if you'd prefer.

    public static string toBinary(int base10)
    {
        string binary = "";
        do {
            binary = (base10 % 2) + binary;
            base10 /= 2;
        }
        while (base10 > 0);

        return binary;
    }

toBinary(10) returns the string "1010".

1
  • This is pretty much the same as Govind's answer (which - to my surprise - is the only equivalent right-to-left iterative answer amongst all these answers) but you're right it's shorter and neater. That said, I'm not sure string prepending like this is going to be very efficient, and you're unlikely to beat the built-in method for efficiency anyway. I also can't see why you'd want to interpret this as an integer number again, but if you did you could do that by constructing the output out of powers of 10 in a similar method to this rather than via a string.
    – Rup
    Sep 23, 2018 at 17:37
1

I came across this problem in a coding challenge where you have to convert 32 digit decimal to binary and find the possible combination of the substring.

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Numerics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp2
{
    class Program
    {

        public static void Main()
        {
            int numberofinputs = int.Parse(Console.ReadLine());
            List<BigInteger> inputdecimal = new List<BigInteger>();
            List<string> outputBinary = new List<string>();


            for (int i = 0; i < numberofinputs; i++)
            {
                inputdecimal.Add(BigInteger.Parse(Console.ReadLine(), CultureInfo.InvariantCulture));
            }
            //processing begins 

            foreach (var n in inputdecimal)
            {
                string binary = (binaryconveter(n));
                subString(binary, binary.Length);
            }

            foreach (var item in outputBinary)
            {
                Console.WriteLine(item);
            }

            string binaryconveter(BigInteger n)
            {
                int i;
                StringBuilder output = new StringBuilder();

                for (i = 0; n > 0; i++)
                {
                    output = output.Append(n % 2);
                    n = n / 2;
                }

                return output.ToString();
            }

            void subString(string str, int n)
            {
                int zeroodds = 0;
                int oneodds = 0;

                for (int len = 1; len <= n; len++)
                {

                    for (int i = 0; i <= n - len; i++)
                    {
                        int j = i + len - 1;

                        string substring = "";
                        for (int k = i; k <= j; k++)
                        {
                            substring = String.Concat(substring, str[k]);

                        }
                        var resultofstringanalysis = stringanalysis(substring);
                        if (resultofstringanalysis.Equals("both are odd"))
                        {
                            ++zeroodds;
                            ++oneodds;
                        }
                        else if (resultofstringanalysis.Equals("zeroes are odd"))
                        {
                            ++zeroodds;
                        }
                        else if (resultofstringanalysis.Equals("ones are odd"))
                        {
                            ++oneodds;
                        }

                    }
                }
                string outputtest = String.Concat(zeroodds.ToString(), ' ', oneodds.ToString());
                outputBinary.Add(outputtest);
            }

            string stringanalysis(string str)
            {
                int n = str.Length;

                int nofZeros = 0;
                int nofOnes = 0;

                for (int i = 0; i < n; i++)
                {
                    if (str[i] == '0')
                    {
                        ++nofZeros;
                    }
                    if (str[i] == '1')
                    {
                        ++nofOnes;
                    }

                }
                if ((nofZeros != 0 && nofZeros % 2 != 0) && (nofOnes != 0 && nofOnes % 2 != 0))
                {
                    return "both are odd";
                }
                else if (nofZeros != 0 && nofZeros % 2 != 0)
                {
                    return "zeroes are odd";
                }
                else if (nofOnes != 0 && nofOnes % 2 != 0)
                {
                    return "ones are odd";
                }
                else
                {
                    return "nothing";
                }

            }
            Console.ReadKey();
        }

    }
}
0
    int x=550;
    string s=" ";
    string y=" ";

    while (x>0)
    {

        s += x%2;
        x=x/2;
    }


    Console.WriteLine(Reverse(s));
}

public static string Reverse( string s )
{
    char[] charArray = s.ToCharArray();
    Array.Reverse( charArray );
    return new string( charArray );
}
0

This was a interesting read i was looking for a quick copy paste. I knew i had done this before long ago with bitmath differently.

Here was my take on it.

// i had this as a extension method in a static class (this int inValue);

public static string ToBinaryString(int inValue)
{
    string result = "";
    for (int bitIndexToTest = 0; bitIndexToTest < 32; bitIndexToTest++)
        result += ((inValue & (1 << (bitIndexToTest))) > 0) ? '1' : '0';
    return result;
}

You could stick spacing in there with a bit of modulos in the loop.

        // little bit of spacing
        if (((bitIndexToTest + 1) % spaceEvery) == 0)
            result += ' ';

You could probably use or pass in a stringbuilder and append or index directly to avoid deallocations and also get around the use of += this way;

1
  • did you test your method, it gives the binary string in reverse
    – Eboubaker
    Nov 11, 2021 at 18:34
0
var b = Convert.ToString(i,2).PadLeft(32,'0').ToCharArray().Reverse().ToArray();
0

Just one line for 8 bit

Console.WriteLine(Convert.ToString(n, 2).PadLeft(8, '0'));

where n is the number

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.