Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the 0xFFFFFFFF doing in this example?

Tags:

swift

swift2

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?

like image 639
James Avatar asked Feb 18 '16 11:02

James


2 Answers

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.

like image 105
BoltClock Avatar answered Nov 06 '22 17:11

BoltClock


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
 */
like image 38
user3441734 Avatar answered Nov 06 '22 16:11

user3441734