Well I want to generate pseudo-random bits for a mathematical problem. The Bit size is user fed. But unlike normal problems there’s a small twist here. The mathematical problem also gives valid results if the bits begin with 0’s and literally match the size input by user.
Example: For User Input 4, all the following are valid outputs:
-> 0000
-> 0001
-> 1000
-> 0100
etc.
I am using this function to generate the numbers now:
int randomChoice = choice.Next(1 << (input - 1), (1 << input) - 1);
bitSize = randomChoice;
Is there any other way of random bit generation that may begin with 0’s as long as it follows the literal bit length in C# without going into complex array manipulation?
The following line:
for
input = 4is equivalent to:Which will per MSDN documentation pick one of the following values: 8, 9, 10, 11, 12, 13, 14 – randomly. Notice that the value 15 will not be picked as the documentation states clearly that the lower bound (8) is )inclusive_ while the upper bound (15) is exclusive.
Those values in binary are:
I believe what @Jon Skeet was saying is that you are generating random numbers that always have the MSB (left-most bit) set. And are thus missing out on all values that fit in 4 bits that would start with 0 (have the MSB unset).
I would also point out that you should probably include value 15 here, since that also fits in the 4 bits. So, with the two modifications, the line of code should read:
That would generate all values from 0 to 15, inclusive:
Is that what you’re looking for?