Python Forum

Full Version: Generate random hex number
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi!
i've a hexa conversion program here :
what i would like to try now is instead of manually throwing in hex number like 0x80 0x0F etc... i would like to generate random hex number and loop it for a few cycles. don't know if this is possible??


D0 = hex(0x80)
D1 = hex(0x0F)
D2 = hex(0x80)

#D0 = Packet[2]
#D1 = Packet[3]
#D2 = Paclet[4]

# hexadecimal coversion
hex = D0
dec0= int(hex, 16)
print('Value in hexadecimal D0:', hex)
print('Value in decimal D0:', dec0)

hex = D1
dec1= int(hex,16)
print('Value in hexadecimal D1:',hex)
print('Value in decimal D1:',dec1)

hex = D2
dec2= int(hex,16)
print('Value in hexadecimal D2:', hex)
print('Value in decimal D2:', dec2)

#coversion ends
Use random.randint to generate a random integer between start and end, where end is inclusive.
Then you can convert the int into a str, which should represent a hex value.

from random import randint

rand_hex_str = hex(randint(0, 255))
print(rand_hex_str)