Numeric type conversions

John Machin sjmachin at lexicon.net
Tue Jun 17 08:07:55 EDT 2008


On Jun 17, 9:28 pm, John Dann <n... at prodata.co.uk> wrote:
> I'm new to Python and can't readily find the appropriate function for
> the following situation:
>
> I'm reading in a byte stream from a serial port (which I've got
> working OK with pyserial) and which contains numeric data in a packed
> binary format. Much of the data content occurs as integers encoded as
> 2 consecutive bytes, ie a 2-byte integer.
>
> I'm guess that there should be a function available whereby I can say
> something like:
>
> My2ByteInt = ConvertToInt(ByteStream[12:13])
>
> to take a random example of the 2 bytes occurring at positions 12 and
> 13 in the byte stream.
>
> Can anyone point me in the right direction towards a suitable function
> please?
>
> NB I don't know without further checking exactly how the bytes are
> encoded, but I'm just transcribing some code across from a Windows
> VB.Net program and these same bytes could be read straight into a
> standard 2-byte signed short int, so I can be confident that it's a
> fairly standard Windows-compatible encoding.

You need the unpack function of the struct module. Supposing you have
a four-byte string containing two such short ints, first + 1 then -1
then this will work:

>>> import struct
>>> two_shorts = '\x01\x00\xff\xff'
>>> struct.unpack('<hh', two_shorts)
(1, -1)
>>>

In the format string, '<' means little-endian (almost universal on PCs
running Windows), and 'h' means a signed 'half-word'. See the struct
manual section for more options.

You can write a function called convert_to_int (take a hint on naming
conventions) and use it a slice at a time, or you can use
struct.unpack to grab a whole record at once. Here's a real live
example of that:

        (
            f.height, option_flags, f.colour_index, f.weight,
            f.escapement_type, f.underline_type, f.family,
            f.character_set,
        ) = unpack('<HHHHHBBB', data[0:13])

HTH,
John





More information about the Python-list mailing list