What is the 0xFFFFFFFF doing in this example?

China☆狼群 提交于 2019-12-12 10:43:59

问题


I understand that arc4random returns an unsigned integer up to (2^32)-1. In this scenario it it always gives a number between 0 and 1.

var x:UInt32 = (arc4random() / 0xFFFFFFFF)

How does the division by 0xFFFFFFFF cause the number to be between 0 - 1?


回答1:


As you've stated,

arc4random returns an unsigned integer up to (2^32)-1

0xFFFFFFFF is equal to (2^32)-1, which is the largest possible value of arc4random(). So the arithmetic expression (arc4random() / 0xFFFFFFFF) gives you a ratio that is always between 0 and 1 — and as this is an integer division, the result can only be between 0 and 1.




回答2:


to receive value between 0 and 1, the result must be floating point value

import Foundation
(1..<10).forEach { _ in
    let x: Double = (Double(arc4random()) / 0xFFFFFFFF)
    print(x)
}
/*
 0.909680047749933
 0.539794033984606
 0.049406117305487
 0.644912529188421
 0.00758233550181201
 0.0036165844657497
 0.504160538898818
 0.879743074271768
 0.980051155663107
 */


来源:https://stackoverflow.com/questions/35479794/what-is-the-0xffffffff-doing-in-this-example

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!