31

How can I convert a binary string, such as 1001101 to Decimal? (77)

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
Gold
  • 60,526
  • 100
  • 215
  • 315

11 Answers11

94

The Convert.ToInt32 method has an overload that accepts a base parameter.

Convert.ToInt32("1001101", 2).ToString();
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
8

Take a look at this questions which is very similar but dealing with hex How to convert numbers between hexadecimal and decimal in C#?

Convert.ToInt64(value, 2)
Community
  • 1
  • 1
John Duff
  • 38,090
  • 5
  • 35
  • 45
5

If you're after a manual way instead of using built in C# libraries, this would work:

static int BinaryToDec(string input)
{
    char[] array = input.ToCharArray();
    // Reverse since 16-8-4-2-1 not 1-2-4-8-16. 
    Array.Reverse(array);
    /*
     * [0] = 1
     * [1] = 2
     * [2] = 4
     * etc
     */
    int sum = 0; 

    for(int i = 0; i < array.Length; i++)
    {
        if (array[i] == '1')
        {
            // Method uses raising 2 to the power of the index. 
            if (i == 0)
            {
                sum += 1;
            }
            else
            {
                sum += (int)Math.Pow(2, i);
            }
        }

    }

    return sum;
}
Pang
  • 9,564
  • 146
  • 81
  • 122
euan jones
  • 121
  • 2
  • 7
  • Which is faster? The built in method or the manual way? Have you tested? – Eric Snyder Jul 07 '19 at 21:04
  • `Math.Pow(2, 0)` is 1, so there is no need for the `if` which will slow it down. – Andrew Morton May 11 '20 at 13:53
  • 2
    Very true Andrew. I'd like to say that it's been a long time since i added this comment and in no way would recommend anyone to use this method. Use C# libraries. I think this was more of a demonstration of how it may logically work. – euan jones May 12 '20 at 14:05
  • IMHO the `if` will not slow it down. It might even speed things up. `Math.Pow` is so much slower than a simple `if` with `int == int`. However, `Math.Pow(2, x)` is usually subject to heavy compiler optimization, as its result is equal to `1 << x`. In which case adding the individual result together is a waste. Better would be to `binary or` the next `1` in and shift right. – TiltonJH Jan 25 '21 at 22:24
2
string s=Console.ReadLine();

int b=Convert.ToInt32(s,2);

Console.WriteLine("Input value in base 10 = "+b);

convert any binary to decimal. :)

MichaelDotKnox
  • 1,312
  • 1
  • 14
  • 17
Mohit
  • 29
  • 3
1

A manual way to convert a binary string to an uint using binary or and shift could be:

  public static uint ConvertBinaryStringToUInt32(string binaryString)
  {
     if (binaryString is null)
     {
        throw new ArgumentNullException(nameof(binaryString));
     }

     if (binaryString.Length > 32)
     {
        throw new ArgumentOutOfRangeException(nameof(binaryString), binaryString.Length, "The specified binary string can not be longer than 32 characters.");
     }

     uint result = 0u;

     for (int i = 0; i < binaryString.Length; i++)
     {
        result <<= 1;

        char c = binaryString[i];

        if (c == '0')
        {
        }
        else if (c == '1')
        {
           result |= 1u;
        }
        else
        {
           throw new FormatException($"Character {i} of binary string \"{binaryString}\" is an invalid '{c}'. Can only be '0' or '1'.");
        }
     }

     return result;
  }
TiltonJH
  • 441
  • 4
  • 6
0

I wanted a solution that always gave 32 bits no matter how big or small the number. So this is what I created.

public static string ConvertUintToBitString(uint Number)
{
    string _BitString = string.Empty;

    if (Number >= 2147483648)
    {
        _BitString += '1';
        Number = Number - 2147483648;
    }
    else
    {
        _BitString += '0';
    }
    if (Number >= 1073741824)
    {
        _BitString += '1';
        Number = Number - 1073741824;
    }
    else
    {
        _BitString += '0';
    }
    if (Number >= 536870912)
    {
        _BitString += '1';
        Number = Number - 536870912;
    }
    else
    {
        _BitString += '0';
    }
    if (Number >= 268435456)
    {
        _BitString += '1';
        Number = Number - 268435456;
    }
    else
    {
        _BitString += '0';
    }
    if (Number >= 134217728)
    {
        _BitString += '1';
        Number = Number - 134217728;
    }
    else
    {
        _BitString += '0';
    }
    if (Number >= 67108864)
    {
        _BitString += '1';
        Number = Number - 67108864;
    }
    else
    {
        _BitString += '0';
    }
    if (Number >= 33554432)
    {
        _BitString += '1';
        Number = Number - 33554432;
    }
    else
    {
        _BitString += '0';
    }
    if (Number >= 16777216)
    {
        _BitString += '1';
        Number = Number - 16777216;
    }
    else
    {
        _BitString += '0';
    }
    if (Number >= 8388608)
    {
        _BitString += '1';
        Number = Number - 8388608;
    }
    else
    {
        _BitString += '0';
    }
    if (Number >= 4194304)
    {
        _BitString += '1';
        Number = Number - 4194304;
    }
    else
    {
        _BitString += '0';
    }
    if (Number >= 2097152)
    {
        _BitString += '1';
        Number = Number - 2097152;
    }
    else
    {
        _BitString += '0';
    }
    if (Number >= 1048576)
    {
        _BitString += '1';
        Number = Number - 1048576;
    }
    else
    {
        _BitString += '0';
    }
    if (Number >= 524288)
    {
        _BitString += '1';
        Number = Number - 524288;
    }
    else
    {
        _BitString += '0';
    }
    if (Number >= 262144)
    {
        _BitString += '1';
        Number = Number - 262144;
    }
    else
    {
        _BitString += '0';
    }
    if (Number >= 131072)
    {
        _BitString += '1';
        Number = Number - 131072;
    }
    else
    {
        _BitString += '0';
    }
    if (Number >= 65536)
    {
        _BitString += '1';
        Number = Number - 65536;
    }
    else
    {
        _BitString += '0';
    }
    if (Number >= 32768)
    {
        _BitString += '1';
        Number = Number - 32768;
    }
    else
    {
        _BitString += '0';
    }
    if (Number >= 16384)
    {
        _BitString += '1';
        Number = Number - 16384;
    }
    else
    {
        _BitString += '0';
    }
    if (Number >= 8192)
    {
        _BitString += '1';
        Number = Number - 8192;
    }
    else
    {
        _BitString += '0';
    }
    if (Number >= 4096)
    {
        _BitString += '1';
        Number = Number - 4096;
    }
    else
    {
        _BitString += '0';
    }
    if (Number >= 2048)
    {
        _BitString += '1';
        Number = Number - 2048;
    }
    else
    {
        _BitString += '0';
    }
    if (Number >= 1024)
    {
        _BitString += '1';
        Number = Number - 1024;
    }
    else
    {
        _BitString += '0';
    }
    if (Number >= 512)
    {
        _BitString += '1';
        Number = Number - 512;
    }
    else
    {
        _BitString += '0';
    }
    if (Number >= 256)
    {
        _BitString += '1';
        Number = Number - 256;
    }
    else
    {
        _BitString += '0';
    }
    if (Number >= 128)
    {
        _BitString += '1';
        Number = Number - 128;
    }
    else
    {
        _BitString += '0';
    }
    if (Number >= 64)
    {
        _BitString += '1';
        Number = Number - 64;
    }
    else
    {
        _BitString += '0';
    }
    if (Number >= 32)
    {
        _BitString += '1';
        Number = Number - 32;
    }
    else
    {
        _BitString += '0';
    }
    if (Number >= 16)
    {
        _BitString += '1';
        Number = Number - 16;
    }
    else
    {
        _BitString += '0';
    }
    if (Number >= 8)
    {
        _BitString += '1';
        Number = Number - 8;
    }
    else
    {
        _BitString += '0';
    }
    if (Number >= 4)
    {
        _BitString += '1';
        Number = Number - 4;
    }
    else
    {
        _BitString += '0';
    }
    if (Number >= 2)
    {
        _BitString += '1';
        Number = Number - 2;
    }
    else
    {
        _BitString += '0';
    }
    if (Number == 1)
    {
        _BitString += '1';
    }
    else
    {
        _BitString += '0';
    }

    return _BitString;
}
  • better way to do this, would be using the method mentioned in the other answers and use String.PadLeft() to add the missing zeros. – Welcor Feb 13 '20 at 19:26
  • (Added the previous comment early) The answer does not fit the question 'binary string -> decimal/int' and not 'uint -> string'. Furthermore instead of contacting the strings use a 'new StringBuilder(32)' and e.g. '.Append('0')'. And instead of subtracting from 'Number' and comparing it use a bit mask like: '(Number & 0x80000000) == 0x80000000' for the highest bit and next '0x40000000' ... . Now the pattern should become visible, so use a 'for' from 0 to i < 32 while shifting the bitMask of the highest bit to the right like 'bitMask >> 1' for each iteration and append the correct char. – TiltonJH Jan 25 '21 at 21:10
  • Result: public static string ConvertUInt32ToBinaryString(uint value) { const uint highestBit = 1u << 31; var sb = new StringBuilder(32); uint bitMask = highestBit; for (int i = 0; i < 32; i++) { if ((value & bitMask) == bitMask) { sb.Append('1'); } else { sb.Append('0'); } bitMask >>= 1; } return sb.ToString(); } – TiltonJH Jan 25 '21 at 21:25
0

I have tried this after reading your problem. It is a bit longer but it provides a solution. I saved binary elements in an array to get a solution. Like I said It is a bit longer, much shorter ways can be found.

        // Binary ------> Decimal 
        int len;
        double deci = 0;

        Console.Write("Length of binary number: ");
        len = Convert.ToInt32(Console.ReadLine());

        int[] bnry = new int[len];

        for (int i = 0; i < len; i++)
        {
            Console.Write("{0} index of binary number: ", i);
            bnry[i] = Convert.ToInt32(Console.ReadLine());
        }
        Console.Write("Your binary number: ");
        for (int i = len - 1; 0 <= i; i--)
        {

            Console.Write(bnry[i]);

        }

        Console.Write("\nDecimal number: ");
        for (int i = 0; i < len; i++)
        {
            deci += (bnry[i] * Math.Pow(2, i));
        }
        Console.Write(deci);
  • 1
    While it’s acceptable to provide code-only answers, it’s often more useful for the community if you can also provide an explanation of the code and help people understand _why_ it addresses the problem. That can reduce the number of follow-up questions, and help new developers understand the underlying concepts. Would you mind updating your question with additional detail? – Jeremy Caney May 10 '20 at 02:01
  • 1
    Yeah sure.Thanks for the advice I am new in StackOverflow I will get used to it over time. – Berkay Eşer May 11 '20 at 13:35
0

I just made an other manual way

private int binary2Decimal(string bin)
    {
        int res;
        char[] cArr = bin.ToCharArray();
        Array.Reverse(cArr); // Reverse binary string
        List<int> iArr = new List<int>();
        for (int i = bin.Length - 1; i > -1; i--) // Get the bits
            iArr.Add(Int16.Parse(cArr[i].ToString()) * (int)Math.Pow(2, i)); // Calculate each bits and add to an array
        res = iArr.ToArray().Sum(); // Calculate all the numbers and add to the final result
        return res;
    }
Gazgoh
  • 1
0
public static int ToDecimal(int n) //1110
    {
        int result = 0;
        var number = n.ToString().ToCharArray();
        var dic = new Dictionary<int, string>();
        var len = number.Length - 1;

        for (int i = 0; i < number.Length && len >= 0; i++)
        {
            dic.Add(i, number[len--].ToString());
        }

        foreach (var item in dic)
        {
            if(Convert.ToInt32(item.Value) > 0 )
            {
                result = result + Convert.ToInt32(Math.Pow(2, item.Key));
            }
        }

        return result;
        
    }
Ajeet Malviya
  • 784
  • 1
  • 5
  • 9
0

This should work

        static int binaryToDecimal(string input) {
         int result = 0;
         for (int i = input.Length; i > 0 ; i--)
             if (input.Substring(i-1,1) == "1")
                 result += (int)Math.Pow(2,(input.Length-i));
         return result;
        }
0

Following code can Convert a binary string with fraction to double. Ex: 0.11 => 0.75

    public static double BinaryToDouble(string binaryString)
    {
        double doubleValue = 0;
        int power = 0;
        var pointIndex = binaryString.IndexOf(".");
        if (pointIndex >= 0)
        {
            var fractionLength = binaryString.Length - pointIndex - 1;
            power = -fractionLength;
        }

        // Iterate over the binary string, starting from the right-most character
        for (int i = binaryString.Length - 1; i >= 0; i--)
        {
            if (binaryString[i] == '1')
            {
                doubleValue += Math.Pow(2, power);
            }

            power++;
        }

        return doubleValue;
    }
Jacob Phan
  • 732
  • 2
  • 6
  • 20