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

Posted on 2009-02-08
Medium Priority
Last Modified: 2012-05-06

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,
Question by:Wally779

Assisted Solution

catchor earned 248 total points
ID: 23583084
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

LVL 10

Accepted Solution

pvginkel earned 252 total points
ID: 23589250
System.Random provides poor random numbers. Please use RNGCryptoServiceProvider:


This also gives you bytes directly.

Author Closing Comment

ID: 31544188
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.

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article introduced a TextBox that supports transparent background.   Introduction TextBox is the most widely used control component in GUI design. Most GUI controls do not support transparent background and more or less do not have the…
Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an anti-spam), the admin…
This lesson discusses how to use a Mainform + Subforms in Microsoft Access to find and enter data for payments on orders. The sample data comes from a custom shop that builds and sells movable storage structures that are delivered to your property. …
Suggested Courses

850 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question