Byte to integer conversion

Lefteris Stamatogiannakis estama at milos.dbnet.ece.ntua.gr
Fri Dec 17 08:28:10 EST 1999


On Thu, 16 Dec 1999, Charles G Waldman wrote:

> Elefterios Stamatogiannakis writes:
>  > 	How can i convert two, three, four bytes into an integer?
>  > 
>  > 	I know a way with pickle, using loads() but i wonder is there
>  > a more elegant way of doing it.
> 
> >>> l = [1,2,3]
> >>> reduce(lambda x,y: x*256+y, l)
> 66051
> 
>  > 	I don't care about big, little endian problems
> 
> If you sudenly start to care about this, you can just reverse/reorder
> the list as needed.
> 
> 
This method is computational intensive. You could use the shift operator
to do the multiplication by 256.

	Faster of all is to do:

	loads("i"+word_string+"\000\000")

	Using marshal (not pickle as i said in my previous mail).

	Anything better?

	I would expect to do something like that using int() or a
variation of that.

The question i'am asking is the same as saying that:

	I received two bytes from a socket. How do i convert them into
an integer in a fast and elegant way?..


Also......

	I have opened a file this way:

	f=open(......)

	I would expect a method like: f.len() to give me the file length.

	There isn't something like that.

	The only way i have found is:

	1. f.seek(0,2)
	   f.tell

	2.Via stat()

	Does anything as simple as f.len() exist?

	Thank you.

	Elefterios Stamatogiannakis.







More information about the Python-list mailing list