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

dman dsh8290@rit.edu
Tue, 11 Sep 2001 06:30:53 -0400


On Tue, Sep 11, 2001 at 12:16:26PM +0530, Ajaya Babu wrote:
| 
| Hi All,
| 
| 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
| i manipulate a integer to a string of two bytes which corresponds to the two
| binary coded bytes of the integer.

Ignacio has shown you the struct module (which I just tried out last
night, pretty coool), but I want to warn you about the differences
between big-endian and little-endian systems.  If the two systems you
are using have different endianness then you will probably run into
problems with the bytes getting reversed.  (I haven't done any playing
with connecting the two so test it thoroughly if you use the struct
module)  The most portable easiest way, I think, and quite easy, from
the python side anyways, is to simply convert the integer to a string
and vice versa.  Ex:  (with C you'd have to use sprintf() and
sscanf())

    # send the number
    an_int = 1234
    try :
        my_socket.write( str( an_int ) )
    except IOError :
        print "Couldn't write to socket!"

    # receive the number
    try :
        raw_data = my_socket.readline() # however you define an
                                        # "entity" in your
                                        # communication protocol
    except IOError :
        print "Couldn't read from socket"
        sys.exit( 1 )

    try :
        an_int = int( raw_data )  # convert the string to an int
    except ValueError :
        print "Invalid data received from socket"
        sys.exit( 1 )

    print "We got %d" % an_int


If you use an existing middleware package such as XML-RPC then you
won't have to deal with any of this low-level communication details.

HTH,
-D