Conversion from string to integer

Mark Warburton Mark.Warburton at gmail.com
Wed Mar 22 20:04:56 CET 2006


You want something like this:

>>> a = '\x1dz'
>>> (ord(a[0])<<8) + ord(a[1])
7546

Each of the two characters represents one byte of a 16-bit integer.  It
doesn't matter if they are ascii or hex -- there are still exactly two
bytes in each of your strings.

The ord() function converts a character to its 8-bit ASCII code.  The
<< operator shifts the first character 8 bits to the left.  Note that
the byte order might need to be swapped, depending on the
implementation of your custom hardware.  e.g.  (ord(a[1])<<8) +
ord(a[0])




More information about the Python-list mailing list