C# changing over the binary string to int: Here, we will figure out how to change over a binary string to its comparable to an integer number in C#?
Given a string that contains a binary value, we need to change over the binary string to an integer in C#.
Changing over from binary string to int
To change over a given binary string into an integer, we use Convert.ToInt32(String, Base/Int32) technique.
Syntax:
Convert.ToInt32(String, Base/Int32);
Here, String is a String object that ought to contain a binary value and Base/Int32 is an integer kind of item which determines the base of the information string.
Here, we are going to change over a binary string to an integer, and the base of the binary is 2. Subsequently, 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 change over 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