generate int from a uuid
Question:
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.
Answers:
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'>
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
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.
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'>
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