I'm trying to get random hex value between range of hexes:
random.randint(0xfff000, 0xffffff)
I got the range limits from JSON, as a string.
{"range": "0xfff000,0xffffff"}
How can I convert these strings(after splitting) to hexadecimal values?
Use the built-in int()
function with a base of 16
:
>>> int('0xfff000', 16)
16773120
>>> int('0xfff000', 16) == 0xfff000
True
You could utilise the following:
from random import randint
d = {"range": "0xfff000,0xffffff"}
print randint(*(int(i, 16) for i in d['range'].split(',')))
# 16775837
And then expand that to customise your own random integer function, eg:
from random import randint
from functools import partial
d = {"range": "0xfff000,0xffffff"}
my_random = partial(randint, *(int(i, 16) for i in d['range'].split(',')))
print [my_random() for n in range(5)]
# [16776381, 16774349, 16776922, 16773212, 16775873]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With