Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python JSON String (containing hex) to HEX

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?

like image 726
0xmtn Avatar asked Sep 01 '25 16:09

0xmtn


2 Answers

Use the built-in int() function with a base of 16:

>>> int('0xfff000', 16)
16773120
>>> int('0xfff000', 16) == 0xfff000
True
like image 164
Andrew Clark Avatar answered Sep 04 '25 05:09

Andrew Clark


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]
like image 23
Jon Clements Avatar answered Sep 04 '25 06:09

Jon Clements