Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 961
user2477784 Avatar asked Jun 12 '13 14:06

user2477784


1 Answers

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]
like image 145
Martijn Pieters Avatar answered Nov 09 '22 08:11

Martijn Pieters