Home > Net >  How can we select a random hex value from a given hex range in python
How can we select a random hex value from a given hex range in python

Time:05-09

If I have a hex range as 0x2080000000-0x217fffffff, and if I need to select a random hex number or multiple hex number from this range, How can I do that using python?

CodePudding user response:

Use randint from the random module:

from random import randint 

x = randint(0x2080000000, 0x217fffffff)
print(f"Decimal    : {x}\n"
      f"Hexadecimal: {hex(x)}")

The above draws a random integer in the closed interval [0x2080000000, 0x217fffffff] and assigns it to x. It then uses the built-in function hex to get the hexadecimal representation (as a string) of integer x.

Sample Output

Decimal    : 140929308832
Hexadecimal: 0x20d00a98a0

Multiple random integers


If you need multiple random integers in the closed interval [0x2080000000, 0x217fffffff] without repetition, you can use sample:

from random import sample

y = sample(range(0x2080000000, 0x2180000000), 10) 

This returns a 10-element list of random integers in the aforementioned closed interval without duplicates. Notice the use of 0x2180000000 instead of 0x217fffffff as range(start, stop) yields integers in the half-open interval [start, stop) so we need to add 0x217fffffff by 1 so that range(0x2080000000, 0x2180000000) yields integers in the closed interval [0x2080000000, 0x217fffffff].

If you do not care about repetition, you can use

y = [randint(0x2080000000, 0x217fffffff) for i in range(10)]

to create a 10-element list of random integers in the closed interval (duplication is possible).

Cryptographically-secure random numbers


If you need cryptographically-secure randomness, first execute (docs)

from random import SystemRandom

rgen = SystemRandom()

Then, instead of

  • using randint(), use rgen.randint();
  • using sample(), use rgen.sample().

CodePudding user response:

Python stores the hex as an int so you can use random.randint() which receives two integers to define a range and returns an integer within the range, then you can cast the resulting integer to a hex.

from random import randint

my_hex = hex(randint(0x2080000000, 0x217fffffff))
print(my_hex)

which prints a random hex:

0x20c30ad886

To pick several hex numbers use random.choices, then cast the resulting integer list into a hex list

from random import choices

hex_list = [hex(i) for i in choices(range(0x2080000000, 0x217fffffff), k=5)]
print(hex_list)

list of hex numbers

['0x2146f52eae', '0x212b07a57c', '0x20afd61152', '0x20e5ad73b9', '0x21620afcb3']
  • Related