Conversion from string to integer

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

You want something like this:

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

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) +

More information about the Python-list mailing list