开发者

How to generate unique 64 bits integers from Python?

开发者 https://www.devze.com 2023-01-12 04:38 出处:网络
开发者_JAVA百科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.
开发者_JAVA百科

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.


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


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.


A 64-bit random number from the OS's random number generator rather than a PRNG:

>>> from struct import unpack; from os import urandom
>>> unpack("!Q", urandom(8))[0]
12494068718269657783L


You can use uuid4() which generates a single random 128-bit integer UUID. We have to 'binary right shift' (>>) each 128-bit integer generated by 64-bit (i.e. 128 - (128 - 64)).

from uuid import uuid4

bit_size = 64
sized_unique_id = uuid4().int >> bit_size
print(sized_unique_id)


Why not try this?

import uuid
  
id = uuid.uuid1()
  
# Representations of uuid1()

print (repr(id.bytes)) # k\x10\xa1n\x02\xe7\x11\xe8\xaeY\x00\x16>\x99\x0b\xdb

print (id.int)         # 142313746482664936587190810281013480411  

print (id.hex)         # 6b10a16e02e711e8ae5900163e990bdb
  
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号