Search code examples
pythonintegerasciisigned

convert ascii character to signed 8-bit integer python


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.


Solution

  • 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]