• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1095
  • Last Modified:

How can I generate random bits or bytes in C# ???


Does anyone know how a clever way to generate random bits or bytes in C# ??? I suppose I could always use the random number generator to generate some random numbers and convert those into a BitArray and then extract the random bits from those random numbers way but I was wondering if there is neater way to do this.

Thank you very much in advance for your time and care,
2 Solutions
You can generate random number from given range, let's say (0...n) and than check whether the generated number is smaller or greater than n/2. Accordingly replace it with 0 or 1
System.Random ran = new System.Random();
//this will generate number in range (1,100)
int number = ran.Next(100);
if (number > 50) 
    return 1;
    return 0;

Open in new window

System.Random provides poor random numbers. Please use RNGCryptoServiceProvider:


This also gives you bytes directly.
Wally779Author Commented:
I thought both solutions were excellent ideas and so I split the points to be awarded to 50% each among both experts who responded. Thank you both very much for your help.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now