4

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?

1
  • Note that "values" are neither decimal, nor binary, nor yet hexidecimal. It is only the representation, e.g. strings, that have place-value at all. Commented Jun 18, 2013 at 17:42

2 Answers 2

10

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

>>> int('0xfff000', 16)
16773120
>>> int('0xfff000', 16) == 0xfff000
True
Sign up to request clarification or add additional context in comments.

2 Comments

+1, I never knew that int accepted strings prefixed like that.
Yeah I had to double check it, was about to write an answer that stripped the 0x off first but it is nice that it isn't necessary.
3

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.