views:

90

answers:

2

I need to generate unique 64 bits integers from Python. I've checked out the UUID module. But the UUID it generates are 128 bits integers. So that wouldn't work.

Do you know of any way to generate 64 bits unique integers within Python? Thanks.

+4  A: 

just mask the 128bit int

>>> import uuid
>>> uuid.uuid4().int & (1<<64)-1
9518405196747027403L
>>> uuid.uuid4().int & (1<<64)-1
12558137269921983654L

These are more or less random, so you have a tiny chance of a collision

Perhaps the first 64 bits of uuid1 is safer to use

>>> uuid.uuid1().int>>64
9392468011745350111L
>>> uuid.uuid1().int>>64
9407757923520418271L
>>> uuid.uuid1().int>>64
9418928317413528031L

These are largely based on the clock, so much less random but the uniqueness is better

gnibbler
uuid1 reveals MAC address and time - uuid4 is more secure.
Lukas Cenovsky
+2  A: 

64 bits unique

What's wrong with counting? A simple counter will create unique values. This is the simplest and it's easy to be sure you won't repeat a value.

Or, if counting isn't good enough, try this.

>>> import random
>>> random.getrandbits(64)
5316191164430650570L

Depending on how you seed and use your random number generator, that should be unique.

You can -- of course -- do this incorrectly and get a repeating sequence of random numbers. Great care must be taken with how you handle seeds for a program that starts and stops.

S.Lott
No matter how good your seeds are you are likely to get repeats after approximately 2^32 IDs have been generated if you use the getrandbits() method.
GregS
The sequence is theoretically longer. "It produces 53-bit precision floats and has a period of 2**19937-1." Why would getrandbits() not have the full period? Does it generate multiple numbers? Even if it generates 64 distinct values and uses only one bit, the resulting period would be 2^311.
S.Lott