How do I generate a random int number?

前端 未结 30 3047
长发绾君心
长发绾君心 2020-11-21 11:02

How do I generate a random integer in C#?

30条回答
  •  Happy的楠姐
    2020-11-21 12:07

    Modified answer from here.

    If you have access to an Intel Secure Key compatible CPU, you can generate real random numbers and strings using these libraries: https://github.com/JebteK/RdRand and https://www.rdrand.com/

    Just download the latest version from here, include Jebtek.RdRand and add a using statement for it. Then, all you need to do is this:

    // Check to see if this is a compatible CPU
    bool isAvailable = RdRandom.GeneratorAvailable();
    
    // Generate 10 random characters
    string key       = RdRandom.GenerateKey(10);
    
     // Generate 64 random characters, useful for API keys 
    string apiKey    = RdRandom.GenerateAPIKey();
    
    // Generate an array of 10 random bytes
    byte[] b         = RdRandom.GenerateBytes(10);
    
    // Generate a random unsigned int
    uint i           = RdRandom.GenerateUnsignedInt();
    

    If you don't have a compatible CPU to execute the code on, just use the RESTful services at rdrand.com. With the RdRandom wrapper library included in your project, you would just need to do this (you get 1000 free calls when you signup):

    string ret = Randomizer.GenerateKey(, "");
    uint ret   = Randomizer.GenerateUInt("");
    byte[] ret = Randomizer.GenerateBytes(, "");
    

提交回复
热议问题