问题描述
我是Swift的新手,只是在教程中看到了用于生成随机角度的代码.
I'm new to Swift and just saw this code used to generate a random angle degree in a tutorial.
func random() ->CGFloat{
return CGFloat(Float(arc4random()) / 0xFFFFFFFF)
}
func random(#min: CGFloat, max:CGFloat) ->CGFloat{
return random()*(max-min)+min
}
我想知道return CGFloat(Float(arc4random()) / 0xFFFFFFFF)
行是否生成0到1.0之间的随机浮点数?那为什么不能只使用drand()?两种功能有什么区别?谢谢!
I'm wondering is the line return CGFloat(Float(arc4random()) / 0xFFFFFFFF)
generates a random float number between 0 and 1.0? Then why cannot just use drand()? Any difference between the two functions? Thanks!
推荐答案
drand48()
适用于许多应用程序,但不安全(换句话说是可预测的). arc4random()
而不完美的设计考虑了安全性.
drand48()
is fine for lots of applications, but is insecure (in other words predictable). arc4random()
while not perfect was designed with security in mind.
我认为苹果因此将人们推向了arc4random()
.因此,回答您的问题:如果您生成随机数以模拟某物,则drand48
应该可以,但是如果您生成随机数以保护某物,则请使用arc4random()
(或者像SecRandomCopyBytes()
这样更安全的东西). ).
I think Apple pushes people to arc4random()
because of that. So, to answer your question: if you are generating random numbers to simulate something, drand48
should be fine, but if you are generating random numbers to protect something, then use arc4random()
(or something even more secure like SecRandomCopyBytes()
).
来自ONLamp的安全编程技术:
这篇关于为什么要使用Float(arc4random())/0xFFFFFFFF而不是drand()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!