[Tutor] long-to-string

Blake Winton bwinton at latte.ca
Mon Oct 20 15:13:41 EDT 2003


I was going to reply, but frankly I just started eating my lunch,
and didn't read email over the weekend.  You might consider being
a little more patient if you send out your messages on a Saturday
or Sunday.

So, you want to convert a long to and from a 4-char string.

The conversion to a long (which you already did) can also be
written as:
>>> struct.unpack( ">l", 'oMAP' )
(1867333968,)

and since we only want the first thing, we write:
>>> struct.unpack( ">l", 'oMAP' )[0]
1867333968

Which leads me to think that the conversion from a long to the
string could be expressed as:
>>> struct.pack( ">l", 1867333968 )
'oMAP'

And we see from the result that it indeed can.

My one final warning is:  If this is intended to help in writing
a Palm program (where 4-character longs are used all over the
place), then you really want the little-endian version of "l" (or
"<l) instead of the big-endian version (or ">l").  If not, then
feel free to ignore this whole paragraph.

Later,
Blake.



> -----Original Message-----
> From: tutor-bounces at python.org 
> [mailto:tutor-bounces at python.org] On Behalf Of Jimmy verma
> Sent: Monday, October 20, 2003 2:41 PM
> To: tutor at python.org
> Subject: Re: [Tutor] long-to-string
> 
> 
> I hope my message reached properly as i have not recieved any 
> response!!!
> 
> 
> 
> >Hello,
> >
> >First of all thanks to tutor for providing their support. 
> People on this 
> >list are really helpful.
> >
> >Now I would like to discuss something about my problem::
> >
> >
> >i have written a module to covert a 4 byte string into a 
> long like this:
> >
> >>>>def makelong(chaine):
> >...     # Make a long form a 4-byte string
> >...     return 
> >((ord(chaine[0])*256+ord(chaine[1]))*256+ord(chaine[2]))*256+
> ord(chaine[3])
> >...
> >>>># Now call the function we just defined:
> >... makelong('oMAP')
> >1867333968
> >
> >
> >I packs this data with struct module
> >
> >using '>L' format
> >
> >I am able to unpack this and get the no from my file
> >
> >Now i want is to convert the no back into the string like 
> >'oMAP' for which this no was meant.
> >
> >I would welcome your suggestions on how should i move ahead.




More information about the Tutor mailing list