简体   繁体   中英

Python random hex generator

So I'm looking to generate a random hex value each time this is called

randhex = "\\x" + str(random.choice("123456789ABCDEF")) + str(random.choice("123456789ABCDEF"))

So far all I've come up with is to make different = calls (ex. randhex1 = ^^, randhex2) etc etc but that's tedious and inefficient and I don't want to do this

ErrorClass = "\\x" + str(random.choice("123456789ABCDEF")) + "\\x" + str(random.choice("123456789ABCDEF")) + "\\x" + str(random.choice("123456789ABCDEF")) + "\\x" + str(random.choice("123456789ABCDEF"))

because that doesn't look good and can be hard to tell how many there are.

I'm trying to assign it to this

ErrorClass = randhex1 + randhex2 + randhex3 + randhex4,
Flags = randhex5,
Flags2 = randhex6 + randhex7,
PIDHigh = randhex2 + randhex5,

and ideally, instead of having to assign different numbers, I want it all to be uniform or something like ErrorClass = randhex*4 which would be clean. If I do this, however, it simply copies the code to be something like this:

Input: ErrorClass = randhex + randhex + randhex + randhex
Output: \xFF\xFF\xFF\xFF

which obviously doesn't work because they are all the same then. Any help would be great.

Make a function that returns the randomly generated string. It will give you a new value every time you call it.

import random

def randhex():
    return "\\x" + str(random.choice("0123456789ABCDEF")) + str(random.choice("0123456789ABCDEF"))

ErrorClass = randhex() + randhex() + randhex() + randhex()
Flags = randhex()
Flags2 = randhex() + randhex()
PIDHigh = randhex() + randhex()

print(ErrorClass)
print(Flags)
print(Flags2)
print(PIDHigh)

Sample result:

\xBF\x2D\xA2\xC2
\x74
\x55\x34
\xB6\xF5

For additional convenience, add a size parameter to randhex so you don't have to call it more than once per assignment:

import random

def randhex(size=1):
    result = []
    for i in range(size):
        result.append("\\x" + str(random.choice("0123456789ABCDEF")) + str(random.choice("0123456789ABCDEF")))
    return "".join(result)

ErrorClass = randhex(4)
Flags = randhex()
Flags2 = randhex(2)
PIDHigh = randhex(2)

print(ErrorClass)
print(Flags)
print(Flags2)
print(PIDHigh)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM