Reputation: 137
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. 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!
Upvotes: 0
Views: 143
Reputation: 18542
First line:
length = random.randint(18, 20)
is 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()
). In this case it means concatenating the bytes 0x02, 0x00 with two strings x
and y
to follow.
x = pack(">b", length)
uses struct.pack()
. In this case, it means to convert the integer value length
into one byte representing its value. It's almost equivalent to using 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. (For example, "@".join(["a","b","c"]) --> "a@b@c"
.)
z = (random.choice(string.printable) for i in range(length))
returns a generator object. 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
.
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
.
Upvotes: 5