dpham
dpham

Reputation: 145

Handling data from Python socket recv

I'm using Python 2.7 sockets to receive data:

data = self.socket.recv(4096)

How do I go about retrieving the first unsigned short from the data? The data looks like this:

>>> print repr(data) 
'\x00\x053B2D4C24\x00\x00\x01\x00...'

Upvotes: 0

Views: 2938

Answers (3)

sqwerty
sqwerty

Reputation: 1773

Old question but thought I'd post a better solution anyway:

value, = struct.unpack('H', data[:2])

Note the , usage in order to correctly unpack the 1-tuple that is returned.

Upvotes: 0

dpham
dpham

Reputation: 145

This is what I came up with:

s = struct.Struct('H')
num = int('0x' + ''.join(x for x in repr(packet[:s.size]) if x.isdigit()), 0)

Upvotes: 0

Santa
Santa

Reputation: 11545

If by unsigned short you mean two bytes, just do:

data[:2]

If you know and expect a certain chunk size of data to parse, you can use the struct library.

Upvotes: 1

Related Questions