c#幾種隨機數組和數組亂序


相關資料MSDN:RNGCryptoServiceProvider   Random   Guid

private static RNGCryptoServiceProvider rngCsp = new RNGCryptoServiceProvider();
static void Main(string[] args)
{
    byte[] byt1 = new byte[16];
    byte[] byt2 = new byte[16];
    byte[] byt3 = new byte[16];
    //加密型強隨機值序列填充字節數組(非零值)
    rngCsp.GetNonZeroBytes(byt1);
    Console.WriteLine("rngCsp.GetNonZeroBytes:");
    Console.WriteLine(ShowBytes(byt1));
    //加密型強隨機值序列填充字節數組
    rngCsp.GetBytes(byt2);
    Console.WriteLine("rngCsp.GetBytes:");
    Console.WriteLine(ShowBytes(byt2));
    //對數組進行隨機填充
    new Random().NextBytes(byt3);
    Console.WriteLine("Random().NextBytes:");
    Console.WriteLine(ShowBytes(byt3));
    //用GUID(UUID)(固定16字節)
    byte[] byt4 = System.Guid.NewGuid().ToByteArray();
    Console.WriteLine("System.Guid:");
    Console.WriteLine(ShowBytes(byt4));
    //亂序
 GetDisorderBytes(byt4);
    Console.WriteLine("GetDisorderBytes:");
    Console.WriteLine(ShowBytes(byt4));
    Console.ReadLine();
}
/// <summary>
/// 亂序排列一個數組
/// </summary>
public static void GetDisorderBytes(byte[] byt)
{
    int min = 1;
    int max = byt.Length;
    int inx = 0;
    byte b = 0;
    Random rnd=new Random ();
    while (min != max)
    {
        int r = rnd.Next(min++, max);
        b = byt[inx];
        byt[inx] = byt[r];
        byt[r] = b;
        inx++;
    }
}
/// <summary>
/// 方便輸出查看
/// </summary>
public static string ShowBytes(byte[] byt)
{
    string s = string.Empty;
    for (int i = 0; i < byt.Length; i++)
        s += string.Format("{0:000}", byt[i]) + " ";
    return s;
}
//輸出
//104 017 080 138 083 174 009 072 048 125 076 075 100 081 155 097 
//rngCsp.GetBytes:
//101 077 221 174 243 202 019 218 110 247 086 020 049 191 060 021 
//Random().NextBytes:
//008 060 247 003 064 156 157 221 207 132 050 216 133 248 172 154 
//System.Guid:
//114 137 072 093 005 222 148 076 155 023 032 029 039 116 099 014 
//GetDisorderBytes:
//148 093 137 222 032 155 116 114 023 076 099 014 072 005 029 039 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM