[英]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到目前为止,我想出的只是进行不同的 = 调用(例如 randhex1 = ^^, randhex2)等,但这既乏味又低效,我不想这样做
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.理想情况下,我不需要分配不同的数字,而是希望它们都是统一的,或者像 ErrorClass = randhex*4 这样干净的东西。 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:为方便起见,向
randhex
添加一个size
参数,这样每次赋值就不必多次调用它:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.