Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate unique 64 bits integers from Python?

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.

like image 208
Continuation Avatar asked Aug 20 '10 11:08

Continuation


People also ask

How do you create a unique number in Python?

To create a random id, you call the uuid4 () method and it will automatically generate a unique id for you just as shown in the example below; Example of usage.

Does Python have 64 bit integers?

Instead, Python uses a variable number of bits to store integers. For example, 8 bits, 16 bits, 32 bits, 64 bits, 128 bits, and so on. The maximum integer number that Python can represent depends on the memory available.

How do you create a unique UUID in Python?

uuid1() function is used to generate a UUID from the host ID, sequence number, and the current time. It uses the MAC address of a host as a source of uniqueness. The node and clock_seq are optional arguments. The node is the hardware address, which is a 48-bit positive integer.

How do you generate multiple UUIDs in Python?

This module provides immutable UUID objects (the UUID class) and the functions uuid1() , uuid3() , uuid4() , uuid5() for generating version 1, 3, 4, and 5 UUIDs as specified in RFC 4122. If all you want is a unique ID, you should probably call uuid1() or uuid4() .


2 Answers

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

like image 85
John La Rooy Avatar answered Sep 25 '22 19:09

John La Rooy


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.

like image 20
S.Lott Avatar answered Sep 22 '22 19:09

S.Lott