使用arc4random获取随机数

Jun 22 2009

通常我们需要获得随机数的时候,假如直接使用了random()就会发现”为什么每次打开程序随机出来结果的顺序都一样?”,这是因为我们获得的随机数实际上都是伪随机数,所以在random之前需要使用srandom()函数获得一个seed来进行随机算法,并且通常是使用srandom(time(NULL)),把时间作为参数是为了获得的seed每次都不一样,当然理论上肯定是不一样的 XD

那么有没有更便捷的随机方法呢?

答案就是使用arc4random,它就藏在C语言标准库(Standard C Library)当中.文档对于它的描述是:

The arc4random() function uses the key stream generator employed by the arc4 cipher, which uses 8*8 8 bit S-Boxes. The S-Boxes can be in about (2**1700) states. The arc4random() function returns pseudo-random numbers in the range of 0 to (2**32)-1, and therefore has twice the range of rand(3) and random(3) .

arc4random既使用了arc4加密算法避免seed重复,并且比random的取值范围(2**31)-1整整大了一倍!那么有什么理由不使用它呢 :-)

arc4random

No responses yet

Leave a Reply