iOS How to get a good random number seed?

jrdoner

macrumors newbie
Original poster
Nov 26, 2009
12
0
Florida
I need a random number generator in an IPhone app, and I want it to seed each time from a new seed, not known to or controlled by the user. In another language development system, the time could be recalled as a floating point number, the fractional part of which could represent the time down to microseconds.

This was ideal, because if you grab the microseconds, convert to an integer, and use it as a seed, it pretty well assured a good, unpredictable result.

Well, I am trying to find this same feature in IPhone XCode, but NSDate (the closest thing I could think of) doesn't seem to offer time below the seconds level.

So is there some other high-resolution clock that I could take advantage of?

Thanks in advance for any help.

John Doner
 

lloyddean

macrumors 65816
May 10, 2009
1,002
16
Des Moines, WA
I believe the following might work as you've described.

Code:
#include <sys/time.h>

struct timeval	tv;
gettimeofday(&tv, NULL);
srand(tv.tv_usec);
 
Comment

admanimal

macrumors 68040
Apr 22, 2005
3,531
2
Depending on how often you need to reseed the generator and exactly how unpredictable you need your results to be, just using the seconds since 1970 or whatever should be more than adequate.
 
Comment

lloyddean

macrumors 65816
May 10, 2009
1,002
16
Des Moines, WA
Depending on how often you need to reseed the generator and exactly how unpredictable you need your results to be, just using the seconds since 1970 or whatever should be more than adequate.
Substitute 'tv_sec' (in my previous code fragment above) for 'tv_usec' and that's what you'll get - seconds since 1970.
 
Comment

firewood

macrumors 604
Jul 29, 2003
7,735
956
Silicon Valley
There are web sites that provide high-entropy random numbers from physically random sources (radioactive decay, turbulent motion, etc.)

For on-device entropy, you could try turning on audio recording from the iPhone mic, and hash a few seconds of background noise samples. Same with the accelerometers if the device is moving.
 
Comment

bredell

macrumors regular
Mar 30, 2008
127
1
Uppsala, Sweden
Well, I am trying to find this same feature in IPhone XCode, but NSDate (the closest thing I could think of) doesn't seem to offer time below the seconds level.

So is there some other high-resolution clock that I could take advantage of?
You can use NSDate. It's true that it counts seconds but it's not an integer. NSDate uses a double precision floating point value with microsecond precision.
 
Comment
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.