chrism1
chrism1

Reputation: 657

Handling output of python socket recv

Apologies for the noob Python question but I've been stuck on this for far too long.

I'm using python sockets to receive some data from a server. I do this:


data = self.socket.recv(4)
print "data is ", data
print "repr(data) is ", repr(data)

The output on the console is this:

data is
repr(data) is '\x00\x00\x00\x01'

I want to turn this string containing essentially a 4 byte number into an int - or actually what would be a long in C. How can I turn this data object into a numerical value that I can easily manage?

Upvotes: 6

Views: 20482

Answers (1)

grieve
grieve

Reputation: 13508

You probably want to use struct.

The code would look something like:

import struct

data = self.socket.recv(4)
print "data is ", data
print "repr(data) is ", repr(data)
myint = struct.unpack("!i", data)[0]

Upvotes: 10

Related Questions