coverting numbers to strings

David Goodger dgoodger at bigfoot.com
Sat May 27 22:05:07 EDT 2000


on 2000-05-27 20:03, Z 3 Penguin (z3penguin at penguinpowered.com) wrote:
> i want to convert an integer to a string contaning the bytes for that value,
> i.e
> 
> >>> a=300
> >>> b= func(a)
> >>> for i in len(b):
> ...    print ord(b[i])
> ...
> 1
> 44

What you want is the "struct" module:

    >>> import struct
    >>> struct.pack("h",300)
    '\001,'
    >>> a = 300
    >>> b = struct.pack("h", a)
    >>> for c in b:
    ...     print ord(c)
    ... 
    1
    44

See the Library Reference for details. Please note that the conversion
string limits the size of the integer (here, "h" is a short integer, two
bytes on my platform). If your value is greater than the converter allows
for, you'll get only the least significant bytes:

    >>> struct.pack("h", 1000000)
    'B@'
    >>> struct.unpack("h", "B@")
    (16960,)
    >>> struct.pack("i", 1000000)
    '\000\017B@'
    >>> struct.unpack("i", "\000\017B@")
    (1000000,)

"i" is for a regular integer, four bytes on my platform.

BTW, Emile, the wierd character sequences you saw were because Penguin's
message was encoded in the Unicode UTF-7 character set. Your email reader
probably doesn't recognize it.

-- 
David Goodger    dgoodger at bigfoot.com    Open-source projects:
 - The Go Tools Project: http://gotools.sourceforge.net
 (more to come!)




More information about the Python-list mailing list