生成随机UINT [英] Generate random uint

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

问题描述

我需要个字节, USHORT 生成一系列随机数为sbyte INT UINT 。我能够为所有那些使用随机方法在C#类型(如 values.Add((INT)(random.Next(int.MinValue + 3,int.MaxValue - 2))); )除以来 Random.Next UINT接受最多只能诠释值。

I need to generate random numbers with range for byte, ushort, sbyte, short, int, and uint. I am able to generate for all those types using the Random method in C# (e.g. values.Add((int)(random.Next(int.MinValue + 3, int.MaxValue - 2)));) except for uint since Random.Next accepts up to int values only.

有没有一种简单的方法来生成随机 UINT

Is there an easy way to generate random uint?

推荐答案

最简单的方法很可能是使用两个呼叫:一个用于30位,一个用于最后两个。这个答案的早期版本假定 Random.Next()有一个的包括的上限的 int.MaxValue ,但事实证明,这是独一无二 - 。所以我们只能够得到30均匀位

The simplest approach would probably be to use two calls: one for 30 bits and one for the final two. An earlier version of this answer assumed that Random.Next() had an inclusive upper bound of int.MaxValue, but it turns out it's exclusive - so we can only get 30 uniform bits.

uint thirtyBits = (uint) random.Next(1 << 30);
uint twoBits = (uint) random.Next(1 << 2);
uint fullRange = (thirtyBits << 2) | twoBits;



(你可以把它在当然两个16位值,作为替代...或在两者之间的各种选项。)

(You could take it in two 16-bit values of course, as an alternative... or various options in-between.)

另外,你可以使用的nextBytes 来填补一个4字节数组,然后使用 BitConverter.ToUInt32

Alternatively, you could use NextBytes to fill a 4-byte array, then use BitConverter.ToUInt32.

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

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