简体   繁体   English

如何从 Python 生成唯一的 64 位整数?

[英]How to generate unique 64 bits integers from Python?

I need to generate unique 64 bits integers from Python.我需要从 Python 生成唯一的 64 位整数。 I've checked out the UUID module .我已经检查了UUID 模块 But the UUID it generates are 128 bits integers.但是它生成的 UUID 是 128 位整数。 So that wouldn't work.所以那行不通。

Do you know of any way to generate 64 bits unique integers within Python?您知道在 Python 中生成 64 位唯一整数的任何方法吗? Thanks.谢谢。

just mask the 128bit int只需屏蔽 128 位 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也许uuid1的前64位使用起来更安全

>>> 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 64 位唯一

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:来自操作系统随机数生成器的 64 位随机数而不是 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.您可以使用uuid4()生成单个随机 128 位整数 UUID。 We have to 'binary right shift' ( >> ) each 128-bit integer generated by 64-bit (ie 128 - (128 - 64) ).我们必须对由 64 位(即128 - (128 - 64) )生成的每个 128 位整数进行“二进制右移”( >> )。

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
  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM