Home » C#.Net

Convert binary string into integer in C#

C# | converting binary string to int: Here, we are going to learn how to convert a binary string to its equivalent to an integer number in C#?
Submitted by IncludeHelp, on March 11, 2019

Given a string that contains binary value, we have to convert binary string to an integer in C#.

Converting from binary string to int

To convert a given binary string into an integer, we use Convert.ToInt32(String, Base/Int32) method.

Syntax:

    Convert.ToInt32(String, Base/Int32);

Here, String is a String object that should contain a binary value and Base/Int32 is an integer type of object which specifies the base of the input string.

Here, we are going to convert a binary string to an integer, and the base of the binary is 2. Thus, the value of Base must be 2.

Example:

    Input:
    string bin_strng = "1100110001";
    Function call:
    Convert.ToInt32(bin_strng, 2);
    Output:
    817

    Input:
    string bin_strng = "10101010101010101010";
    Function call:
    Convert.ToInt32(bin_strng, 2);
    Output:
    699050

C# code to convert a binary string to an integer

using System;
using System.Text;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            string bin_strng = "1100110001";
            int number = 0;

            number = Convert.ToInt32(bin_strng, 2);
            Console.WriteLine("Number value of binary \"{0}\" is = {1}",
                bin_strng, number);

            bin_strng = "1111100000110001";
            number = Convert.ToInt32(bin_strng, 2);
            Console.WriteLine("Number value of binary \"{0}\" is = {1}",
                bin_strng, number);

            bin_strng = "10101010101010101010";
            number = Convert.ToInt32(bin_strng, 2);
            Console.WriteLine("Number value of binary \"{0}\" is = {1}",
                bin_strng, number);


            //hit ENTER to exit
            Console.ReadLine();
        }
    }
}

Output

Number value of binary "1100110001" is = 817
Number value of binary "1111100000110001" is = 63537
Number value of binary "10101010101010101010" is = 699050



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.