[Tutor] How to convert integer to binay packed string...,?

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Tue, 11 Sep 2001 12:03:42 -0700 (PDT)


On Tue, 11 Sep 2001, Ajaya Babu wrote:

> I've a small doubt, How to convert integers into bytestream in python.
> What actually I want to do is send integer to another system in the
> network. But since there is nothing like integer in python...I am just
> wondering how can

Actually, Python Integers are 32-bit integers, and we can do bitwise
manipulation with them:

###
>>> x = 2
>>> x>>2
0
>>> x<<2
8
>>> 0xffffffff & 0x00002000
8192
###

As Ignacio as mentioned, it sounds like you'll want to look at the
"struct" module, a module that deals exclusively with packing things into
bytes.


Alternatively, you might want to look at the "pickle" module:

    http://python.org/doc/current/lib/module-pickle.html

pickle will allow us to preserve integers into strings --- in effect, it
turns things into a bytestream.  pickle will "serialize" Python objects
into something that we can save, or send!  If you're sending something
across the network to another Python system, pickle might be useful for
you.

Hope this helps!