0

I would like to generate a "random" int from a given uuid. All I care about is that given the uuid, I will always get the same int.

I'm aware that the range of uuids is much largers than the range of ints in python, so I'm taking the risk of 2 different uuids generating the same int, but it's a risk I'm willing to take.

So my question is what is the best way to generate such int from a given uuid? I know I can just maybe use the uuid as a seed to random() and just generate a random int, but wondered if there is a "cleaner" solution.

AcK
  • 2,063
  • 2
  • 20
  • 27
tamirg
  • 607
  • 1
  • 7
  • 15
  • 1
    Does this answer your question? [python hash function that returns 32 (or 64) bits](https://stackoverflow.com/questions/67219691/python-hash-function-that-returns-32-or-64-bits) – Joe Jan 24 '22 at 11:19
  • https://stackoverflow.com/questions/7604966/maximum-and-minimum-values-for-ints may also be relevant – Joe Jan 24 '22 at 11:23
  • "the range of uuids is much largers than the range of ints in python" - Lol. No. How did you get that idea? – Kelly Bundy Jan 24 '22 at 14:30

2 Answers2

5

You can actually convert uuids to ints on python very easily:

>>> import uuid
>>> int(uuid.uuid4())
101044264907663221935019178350016176435

Yeah, it's a really big number, but hey, it will "never" be repeated and the solution is as clean as it could be.

Edit: Keep in mind that this is for python 3. On python 2 this also works, BUT, the number you'll obtain will be long instead of int:

>>> import uuid
>>> int(uuid.uuid4())
314613414059294171759586868273801197923L
>>> type(int(uuid.uuid4()))
<type 'long'>
Shinra tensei
  • 1,283
  • 9
  • 21
1

UUID objects also have an int property that you can directly call. For example:

import uuid
print(uuid.uuid4().int)

The int property returns a 128 bit integer.

Source: https://docs.python.org/3/library/uuid.html#uuid.UUID.int

Sam Stoelinga
  • 4,881
  • 7
  • 39
  • 54