Is there a more elegant way of doing the bit size selection and pseudo-random binary bit generation than I am doing here? Actually I need to write an algorithm where the user is in control of the bit size (max 16 bit) of the random binary bit generated. This is the function I wrote however I am not sure if this is the smallest/most elegant. As this is scientific in need efficiency doesn't matter much but elegance of code and easy understandability does matter. So is there a more efficient/elegant way of doing the same?
Also as a second question, if I press Enter twice when the code is asking for bit size, it returns an exception error. Is there a way to bypass the same?
Thanks.
private static string randomBit() { int bitSize = 0, input = 0; Console.Write("Input Bit Size (Maximum is 16 Bit): "); input = Convert.ToInt32(Console.ReadLine()); Random choice = new Random(); if (input == 0 || input > 16) { bitSize = 0; } else if (input == 1) { bitSize = 1; } else if (input == 2) { int randomChoice = choice.Next(2, 3); bitSize = randomChoice; } else if (input == 3) { int randomChoice = choice.Next(4, 7); bitSize = randomChoice; } else if (input == 4) { int randomChoice = choice.Next(8, 15); bitSize = randomChoice; } else if (input == 5) { int randomChoice = choice.Next(16, 31); bitSize = randomChoice; } else if (input == 6) { int randomChoice = choice.Next(32, 63); bitSize = randomChoice; } else if (input == 7) { int randomChoice = choice.Next(64, 127); bitSize = randomChoice; } else if (input == 8) { int randomChoice = choice.Next(128, 255); bitSize = randomChoice; } else if (input == 9) { int randomChoice = choice.Next(256, 511); bitSize = randomChoice; } else if (input == 10) { int randomChoice = choice.Next(512, 1023); bitSize = randomChoice; } else if (input == 11) { int randomChoice = choice.Next(1024, 2047); bitSize = randomChoice; } else if (input == 12) { int randomChoice = choice.Next(2047, 4095); bitSize = randomChoice; } else if (input == 13) { int randomChoice = choice.Next(4096, 8191); bitSize = randomChoice; } else if (input == 14) { int randomChoice = choice.Next(8192, 16383); bitSize = randomChoice; } else if (input == 15) { int randomChoice = choice.Next(16384, 32767); bitSize = randomChoice; } else if (input == 16) { int randomChoice = choice.Next(32768, 65535); bitSize = randomChoice; } string binary = Convert.ToString(bitSize, 2); return binary; }
Also as a second question, if I press Enter twice when the code is asking for bit size, it returns an exception error. Is there a way to bypass the same?
Thanks.