6

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?

1 Answer 1

10

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]
Sign up to request clarification or add additional context in comments.

3 Comments

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.
Just to be pedantic, I believe the last line should also be: myint = struct.unpack("!i", data)[0]

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.