开发者

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


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.


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)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜