c# convert binary string to integer
// How to generate a random binary number
public static int rndNumber = 0;
public static int answerInt = 0;
public static string fullStr = null;
public static string answerStr = null;
static void Main(string[] args)
{
Console.Write("Random binary number: ");
Random r = new Random();
// The 'ctr <= 3' part of the program means the binary number will
// have a length of 4. The for loop will loop until ctr == 4.
for (int ctr = 0; ctr <= 3; ctr++)
{
// Generate either 0 or 1
rndNumber = r.Next(0, 2);
Console.Write(rndNumber);
// Convert rndNumber int to string and append number to str
string numStr = rndNumber.ToString();
fullStr += numStr;
}
// Convert str to int and return answer
answerInt = Convert.ToInt32(string.Format("{0}", fullStr));
Console.WriteLine("nInt: " + answerInt);
answerStr = answerInt.ToString("D4");
Console.WriteLine("String: " + answerStr);
}
// OUTPUT:
Random binary number: 0010
Int: 10
String: 0010