Reputation: 1827
I need an algorithm that pretty much will turn a unix timestamp into a suitably random number, so that if I "play back" the timestamps I get the same random numbers.
And here's what I mean by suitably:
And I would like it to be fairly fast.
So far my idea is to just seed a PRNG over and over, but I'm not sure if that's the best way to handle this.
Any thoughts and ideas will be much appreciated.
Thanks.
Upvotes: 1
Views: 719
Reputation: 204698
I would suggest that the easiest thing to do is feed your time to jrand48. Something like
#include <stdlib.h>
int mix(int t) {
unsigned short x[3] = {t, t<<16, t};
return jrand48(x);
}
It's reversible (216·x+n≡0x5deece66d·(232+1)·t+0xb mod 248 ⇒ t≡0xdfe05bcb1365·(216·x+n-0xb) mod 248 where n∈[0,216)) but since it's the high 32 bits out of 48-bit, it's actually not too easy. (You can apply jrand48
to x
more than once too; as long as you don't apply it 248-1 times, the same sorts of properties will hold.)
Upvotes: 1
Reputation: 12560
(timestamp ^ 0x12345678) + 12345678
Is this subtle enough?
If you don't care about reversibility of it you could crc32 each timestamp.
Upvotes: 0
Reputation: 753675
I suggest looking at the POSIX-compliant drand48()
family of functions. They give decent (but certainly not cryptographic) random numbers, and srand48()
takes a 32-bit seed value. They are deterministic, so reusing a given seed will regenerate the same sequence of numbers again.
Upvotes: 0
Reputation: 77400
If it doesn't need to be statistically random, perhaps feed the timestamps to MD5 and truncate the hash. The main issue is that I don't know if this would be surjective. Other hashing algorithms might work better.
Upvotes: 2