[英]Python - can someone tell me what these two lines do?
I'm trying to convert this Python code to C. But for the life of me, I can't figure out what this line here does. 我正在尝试将此Python代码转换为C。但是对于我一生来说,我不知道这里的代码是做什么的。 The rest of the program seems simple.
该程序的其余部分似乎很简单。
self.payload = "\x02\x00%s%s" % (
pack(">b", length),
"".join(random.choice(string.printable) for i in range(length)))
If anybody could give me a rough idea of what this is doing, it'd be much appreciated! 如果有人可以粗略地了解我在做什么,那将不胜感激!
First line: 第一行:
length = random.randint(18, 20)
is int length = rand() % 3 + 18
. length = random.randint(18, 20)
的正确翻译是int length = rand() % 3 + 18
。 Now let's dissect the dense second line piece by piece. 现在,让我们逐一剖析密集的第二行。
"\\x02\\x00%s%s" % (x, y)
means to substitute the format string with the given arguments (like sprintf()
). "\\x02\\x00%s%s" % (x, y)
表示用给定的参数替换格式字符串(例如sprintf()
)。 In this case it means concatenating the bytes 0x02, 0x00 with two strings x
and y
to follow. 在这种情况下,这意味着将字节0x02、0x00与两个字符串
x
和y
串联在一起。
x = pack(">b", length)
uses struct.pack()
. x = pack(">b", length)
使用struct.pack()
。 In this case, it means to convert the integer value length
into one byte representing its value. 在这种情况下,这意味着将整数
length
转换为一个代表其值的字节。 It's almost equivalent to using chr()
. 这几乎等同于使用
chr()
。
y = "".join(z)
means to take each element in the list z
(which must be a string) and concatenate them with "" (nothing) between them. y = "".join(z)
表示将列表z
中的每个元素(必须是字符串)并以“”(它们之间没有任何内容)连接起来。 (For example, "@".join(["a","b","c"]) --> "a@b@c"
.) (例如,
"@".join(["a","b","c"]) --> "a@b@c"
。)
z = (random.choice(string.printable) for i in range(length))
returns a generator object. z = (random.choice(string.printable) for i in range(length))
返回一个生成器对象。 You can think of it as a list whose elements are computed on demand. 您可以将其视为按需计算元素的列表。 In this case, it generates
length
elements where each element is one character randomly chosen from the string string.printable
. 在这种情况下,它将生成
length
元素,其中每个元素都是从字符串string.printable
随机选择的一个字符。
All in all, the second line yields a string that starts wxth 0x02 0x00, followed by (char)length
, followed by length
random characters each uniformly chosen from the set of chars string.printable
. 总而言之,第二行产生一个以wxth 0x02 0x00开头的字符串,然后是
(char)length
,然后是length
随机字符,每个字符都是从chars string.printable
集合中统一选择的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.