tags:

views:

1185

answers:

1

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?

+7  A: 

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]
grieve
Thanks. I actually had to do "myint = unpack("!i", data)[0]" since it's big-endian and it comes out as a tuple. If you want to edit I'll mark your answer correct. Again, thanks for the help.
Missed the tuple part. :) Edited the answer per your request.
grieve
Just to be pedantic, I believe the last line should also be: myint = struct.unpack("!i", data)[0]
Jason Baker
Oops! didn't notice that. Fixed! Thanks for pointing it out.
grieve