jeudi 16 novembre 2017

How can I generate a random binary number?

I created a binary-to-decimal converter.

    using System;

namespace binary
{
class Program
{
    static void Main(string[] args)
    {

        string ranBi = "1010010";

        int decimal = 0;
        for (int i = 0; i < ranBi.Length; i++)
        {
            if (ranBi[ranBi.Length - i - 1] == '0') continue;
            decimal += (int)Math.Pow(2, i);
        }

        Console.WriteLine($"The randomly generated binary number converted to decimal is: {decimal}.");

        Console.ReadKey();
    }
}
}

I would like to be able to convert a randomly generated binary number (let's say between 2 and 10 digits), but I cannot seem to do it. Would it work if I randomly generated a string with 0-s and 1-s in it? (And if so, how could I implement that?)

Thanks for the help!




Aucun commentaire:

Enregistrer un commentaire