बाइनरी स्ट्रिंग को पूर्णांक में बदलने के अपने उद्देश्य को पूरा करने के लिए Convert.ToInt32 वर्ग का उपयोग करें।
मान लें कि हमारी बाइनरी स्ट्रिंग है -
string str = "1001";
अब प्रत्येक चार को पार्स किया गया है -
try {
//Parse each char of the passed string
val = Int32.Parse(str1[i].ToString());
if (val == 1)
result += (int) Math.Pow(2, str1.Length - 1 - i);
else if (val > 1)
throw new Exception("Invalid!");
} catch {
throw new Exception("Invalid!");
} पारित स्ट्रिंग में प्रत्येक वर्ण के लिए उपरोक्त की जाँच करें अर्थात "100" लूप के लिए का उपयोग करके। लंबाई () विधि का उपयोग करके स्ट्रिंग की लंबाई ज्ञात करें -
str1.Length
उदाहरण
आप बाइनरी स्ट्रिंग को C# में एक पूर्णांक में बदलने के लिए निम्न कोड को चलाने का प्रयास कर सकते हैं।
using System;
class Program {
static void Main() {
string str = "1001";
Console.WriteLine("Integer:"+ConvertClass.Convert(str));
}
}
public static class ConvertClass {
public static int Convert(string str1) {
if (str1 == "")
throw new Exception("Invalid input");
int val = 0, res = 0;
for (int i = 0; i < str1.Length; i++) {
try {
val = Int32.Parse(str1[i].ToString());
if (val == 1)
res += (int)Math.Pow(2, str1.Length - 1 - i);
else if (val > 1)
throw new Exception("Invalid!");
} catch {
throw new Exception("Invalid!");
}
}
return res;
}
} आउटपुट
Integer:9