C#3.5中的8位随机数生成 [英] 8 Digit Random Number Generation in C#3.5

查看:591
本文介绍了C#3.5中的8位随机数生成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我需要在C#3.5中生成8位数字的随机数.由于随机数是可以预测的,因此我不想使用syste.random类.

所以我使用了密码随机数的生成方法,但这总是给我随机的字节数.我期望从这些随机字节中得到8位数字的随机数,是否有可能从这些随机字节中得到正随机数和8位数字的随机数.

谢谢,
Uday

Hi All,

I have a requirement to generate the 8 digit random number in C#3.5.I do not want to use the syste.random class since the random number can predictable.

So I used Cryptographic random number genearation but this gives me always random bytes only.Iam expecting an 8 digit random number from these random bytes.Is there any possibility getting only possitive random bytes and 8 digit random number from these random bytes.

Thanks,
Uday

推荐答案

首先,我不认为System.Random给出可预测的结果.如果您这样说,请您证明您的预测?但是,我不确定随机生成的结果是否不相关并且服从所需的分布.即使不完美,也并不意味着可预测性.

现在,假设您有随机字节.假设您的方法是byte Random().

First of all, I don''t think System.Random gives predictable results. If you say so, would you please demonstrate your prediction? However, I''m not sure if the result of random generation is not correlated and obey required distribution. Even if it not perfect, it does not mean predictability.

Now, let''s assume you have random byte. Let''s say your method is byte Random().

int RandomInt() {
    byte numBytes = sizeof(int);
    int value = 0;
    for (int index = 0; index < numBytes; index ++)
       value |= Random() << index * 8;
    return value;
}



与其他任何整数类型相同.您所需要做的就是将每个字节移位所需的位数,以按顺序将其放入所有字节位置,或与先前结果进行或运算.由于字节数是根据目标类型计算得出的,因此无论您要用作目标的哪种类型都可以使用,但是...写一个泛型(以一种简单的方式)几乎是不可能的.

—SA



Same thing with any other integer type. All you need is to shift each byte by the number of bits need to put it in all byte positions in sequence and OR with previous result. As number of bytes is calculated from the target type, it will work no matter what type you want to use as a target but... to write a generic (in a simple way) is nearly impossible.

—SA


哦!请集中精力,正确看一下界面和类型!

回答后续问题:

Oh! Please concentrate, look at the interface and types properly!

To answer follow-up question:

int RandomInt(RNGCryptoServiceProvider random) {
    byte numBytes = sizeof(int);
    byte randomBytes = byte[numBytes];
    random.GetBytes(randomBytes);
    int value = 0;
    for (int index = 0; index < numBytes; index ++)
       value |= randomBytes[index] << index * 8;
    return value;
}



您没有看到byte[]byte之间的区别吗?他们如何转换?
不要实现我的Random,仅举例来说,立即随机化所有numBytes (==4)字节(如上所示).

—SA



Didn''t you see the difference between byte[] and byte?! How could they convert?
Don''t implement my Random, it was just for example, make random all numBytes (==4) bytes at once (shown above).

—SA


也许您可以在本文的一部分中使用它生成随机加密密钥:

创建并共享(使用客户端应用)随机加密密钥 [
Maybe you could use part of this article where it generates a random encryption key:

Create and Share (with a client app) a Random Encryption Key[^]


这篇关于C#3.5中的8位随机数生成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆