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

Posted on 2009-02-08
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

    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

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

    This also gives you bytes directly.

    Author Closing Comment

    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

    How your wiki can always stay up-to-date

    Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
    - Increase transparency
    - Onboard new hires faster
    - Access from mobile/offline

    Join & Write a Comment

    Article by: Najam
    Having new technologies does not mean they will completely replace old components.  Recently I had to create WCF that will be called by VB6 component.  Here I will describe what steps one should follow while doing so, please feel free to post any qu…
    We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can…
    how to add IIS SMTP to handle application/Scanner relays into office 365.
    Internet Business Fax to Email Made Easy - With eFax Corporate (, you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…

    734 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

    Need Help in Real-Time?

    Connect with top rated Experts

    18 Experts available now in Live!

    Get 1:1 Help Now