gpt4 book ai didi

c# - 如何使用 System.Security.Cryptography 生成随机 int 值

转载 作者:行者123 更新时间:2023-11-30 20:34:49 25 4
gpt4 key购买 nike

我想使用 System.Security.Cryptography 生成从 0 到 26 的随机 int 值,我该怎么做?我知道可以使用 system.random 来做到这一点,但我想使用 System.Security.Cryptography

最佳答案

您可以使用它从 Crypto RNG 生成随机整数。但是,我很难解释这种工具在密码学之外的场景。

RNGCryptoServiceProvider CprytoRNG = new RNGCryptoServiceProvider();

// Return a random integer between a min and max value.
int RandomIntFromRNG(int min, int max)
{
// Generate four random bytes
byte[] four_bytes = new byte[4];
CprytoRNG.GetBytes(four_bytes);

// Convert the bytes to a UInt32
UInt32 scale = BitConverter.ToUInt32(four_bytes, 0);

// And use that to pick a random number >= min and < max
return (int)(min + (max - min) * (scale / (uint.MaxValue + 1.0)));
}

关于c# - 如何使用 System.Security.Cryptography 生成随机 int 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38668748/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com