在C#中将二进制字符串转换为整数
给定一个包含二进制值的字符串,我们必须在C#中将二进制字符串转换为整数。
从二进制字符串转换为int
要将给定的二进制字符串转换为整数,我们使用Convert.ToInt32(String,Base/Int32)方法。
语法:
Convert.ToInt32(String, Base/Int32);
在这里,String是应该包含二进制值的String对象,而Base/Int32是整数类型的对象,用于指定输入字符串的基数。
在这里,我们将二进制字符串转换为整数,二进制的底数为2。因此,Base的值必须为2。
示例
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#代码将二进制字符串转换为整数
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); //按ENTER退出 Console.ReadLine(); } } }
输出结果
Number value of binary "1100110001" is = 817 Number value of binary "1111100000110001" is = 63537 Number value of binary "10101010101010101010" is = 699050