redesert17 redesert17 - 1 month ago 8
Python Question

Struct.pack sends array instead just single int variable

I have

check_paket = 0

check_paket = fragIndex
check_header = struct.pack('!I', check_paket)
sock.sendto(check_header, (host, port))


And when I receive and unpack

check_fragIndex = 0

data, addr = self.sock.recvfrom(65489)
check_header = data[:4]
(check_fragIndex) = struct.unpack('!I', check_header)
print('SENDER: check_fragIndex:' +str(check_fragIndex))


fragIndex
is set for example to
1
when sending so it prints this

SENDER: check_fragIndex:(1,)


Instead of
SENDER: check_fragIndex: 1


It creates a string I guess, but why? I need that
fragIndex
as 4 byte integer number...

Answer

struct.unpack() always returns a tuple. From the documentation:

The result is a tuple even if it contains exactly one item.

You appear to try to use assignment to extract the one value, but you only used parentheses:

(check_fragIndex) = struct.unpack('!I', check_header)

(check_fragIndex) is just a parenthesised name, not a tuple, so no extraction is taking place; check_fragIndex is bound to the whole tuple that struct.unpack() returns. You need a comma to get that effect:

(check_fragIndex,) = struct.unpack('!I', check_header)
#               ^ the comma is crucial here

You can omit the parentheses altogether:

check_fragIndex, = struct.unpack('!I', check_header)

or just use indexing to extract the one result:

check_fragIndex = struct.unpack('!I', check_header)[0]