3

with this code :

let rand : Int = Int(arc4random())
NSLog("rand = %d %i %@ \(rand)",rand,rand,String(rand))

I get :

rand = -1954814774 -1954814774 2340152522 2340152522

why all 4 values are not the same ?

Gogo123
  • 655
  • 1
  • 4
  • 11
  • maybe linked to func arc4random() -> UInt32 but why ? – Gogo123 Dec 02 '20 at 12:19
  • Maybe it has smth to do with signed vs unsigned? Int & Double are signed, the string interpretations are not – Deitsch Dec 02 '20 at 12:21
  • according to https://developer.apple.com/documentation/swift/int Int is a signed integer value type. – Gogo123 Dec 02 '20 at 12:22
  • "On 32-bit platforms, Int is the same size as Int32, and on 64-bit platforms, Int is the same size as Int64." so there 's probably a link with 32 / 64 bits but I still don't understand what's the value of rand – Gogo123 Dec 02 '20 at 12:24

1 Answers1

2

arc4random generates an unsigned 32bit int. Int is probably 64 bit on your machine so you get the same number and it doesn't overflow. But %i and %d are signed 32-bit format specifiers. See here and here. That's why you get a negative number when arc4random returns a number greater than 2^32-1, aka Int32.max.

For example, when 2340152522 is generated, you get -1954814774 in the %i position because:

Int32(bitPattern: 2340152522) == -1954814774

On the other hand, converting an Int to String won't change the number. Int is a signed 64 bit integer.

Sweeper
  • 213,210
  • 22
  • 193
  • 313