convert ascii character to signed 8-bit integer python

user2477784 picture user2477784 · Jun 12, 2013 · Viewed 10k times · Source

This feels like it should be very simple, but I haven't been able to find an answer..

In a python script I am reading in data from a USB device (x and y movements of a USB mouse). it arrives in single ASCII characters. I can easily convert to unsigned integers (0-255) using ord. But, I would like it as signed integers (-128 to 127) - how can I do this?

Any help greatly appreciated! Thanks a lot.

Answer

Martijn Pieters picture Martijn Pieters · Jun 12, 2013

Subtract 256 if over 127:

unsigned = ord(character)
signed = unsigned - 256 if unsigned > 127 else unsigned

Alternatively, repack the byte with the struct module:

from struct import pack, unpack
signed = unpack('B', pack('b', unsigned))[0]

or directly from the character:

signed = unpack('B', character)[0]