How to convert bytearray into integer?

Thomas Jollans thomas at jollybox.de
Fri Aug 20 15:36:31 EDT 2010


On Tuesday 17 August 2010, it occurred to Jacky to exclaim:
> On Aug 17, 3:38 am, Thomas Jollans <tho... at jollybox.de> wrote:
> > On Monday 16 August 2010, it occurred to Jacky to exclaim:
> > > it's hard to image why socket object provides the interface:
> > > socket.recv_from(buf[, num_bytes[, flags]]) but forget the more
> > > generic one: socket.recv_from(buf[, offset[, num_bytes[, flags]]])
> > 
> > Well, that's what pointer arithmetic (in C) or slices (in Python) are
> > for! There's an argument to be made for sticking close to the
> > traditional (originally C) interface here - it's familiar.
> 
> Hi Thomas, - I'm not quite follow you.  It will be great if you could
> show me some code no this part...

When I originally wrote that, I didn't check the Python docs, I just had a 
quick look at the manual page.

This is the signature of the BSD-socket recv function: (recv(2))

       ssize_t recv(int sockfd, void *buf, size_t len, int flags);

so, to receive data into a buffer, you pass it the buffer pointer.

	len = recv(sock, buf, full_len, 0);

To receive more data into another buffer, you pass it a pointer further on:

	len = recv(sock, buf+len, full_len-len, 0);
	/* or, this might be clearer, but it's 100% the same: */
	len = recv(sock, & buf[len], full_len-len, 0);

Now, in Python. I assume you were referring to socket.recv_into:

		socket.recv_into(buffer[, nbytes[, flags]])

It's hard to imagine why this method exists at all. I think the recv method is 
perfectly adequate:

	buf = bytearray()
	buf[:] = sock.recv(full_len)
	# then:
	lngth = len(buf)
	buf[lngth:] = sock.recv(full_len - lngth)

But still, nothing's stopping us from using recv_into:

	# create a buffer large enough. Oh this is so C...
	buf = bytearray([0]) * full_len
	lngth = sock.recv_into(buf, length_of_first_bit)
     # okay, now let's fill the rest !
	sock.recv_into(memoryview(buf)[lngth:])

In C, you can point your pointers where ever you want. In Python, you can 
point your memoryview at buffers in any way you like, but there tend to be 
better ways of doing things.

Cheers,

	Thomas



More information about the Python-list mailing list