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
  • 1,870
  • 1
  • 17
  • 22
tamirg
  • 369
  • 2
  • 10
  • 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

1 Answers1

3

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,246
  • 9
  • 21