2진 문자열을 정수로 변환하려는 목적을 달성하려면 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!");
} for 루프를 사용하여 전달된 문자열의 각 문자, 즉 "100"에 대해 위를 확인하십시오. length() 메서드를 사용하여 문자열의 길이 찾기 -
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