0

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...'

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Yea that's the obvious answer. There might be a more elegant way of doing it but for now I'm going with a variation of what you have.
0

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)

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.