VAAA VAAA - 2 months ago 13
C# Question

C# generate bit string randomly "0001", "1010", etc

I need to generate a 4 bit string randomly and set to a property via Linq.

Right now is hardcoded:

// TODO: hardcode bit string
employees = employees.Select(x => { x.Options = "0101"; return x; }).ToList();

I need Options to be random so I can get all 4 bit possible values: "0001","0010", "0011" and so on.

I was thinking on having a Random
variable and generate the value 4 times and concatenate the string.

Any clue on how to implement this?

var rand = new Random();
Convert.ToString(rand.Next(16), 2).PadLeft(4, '0')


The first line creates a random object, nothing too hard to understand here... The second line first generates a random number between 0 - 15 (rand.Next(16)). Then it puts the random number into Convert.ToString. The method converts to number to base 2 (because the second parameter is 2). However, this still is not enough because if the random number can be represented by 3 bits or fewer, the returned string will not have the leading 0s. That's why I used PadLeft to add them in.