Convert ascii character to signed 8-bit integer python

It sounds like it should be very simple, but I could not find the answer.

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

Any help is much appreciated! Thank you very much.

+4
source share
4 answers

Subtract 256 if above 127:

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

As an alternative, repack bytes using the struct module:

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

or directly from the symbol:

 signed = unpack('B', character)[0] 
+4
source
 from ctypes import c_int8 value = c_int8(191).value 

use ctypes with your ord () value - in this case should be -65

ex. from string data

 from ctypes import c_int8 data ='BF' value1 = int(data, 16) # or ord(data.decode('hex')) value2 = c_int8(value1).value 

value1 is a 16-bit integer representation of hex 'BF', and value2 is an 8-bit representation

0
source

I know this is an old question, but I did not find a satisfactory answer elsewhere.

You can use the array module (with the added convenience of converting full buffers):

 from array import array buf = b'\x00\x01\xff\xfe' print(array('b', buf)) # result: array('b', [0, 1, -1, -2]) 
0
source

Use this function to get a signed 8-bit integer value.

 def to8bitSigned(num): mask7 = 128 #Check 8th bit ~ 2^8 mask2s = 127 # Keep first 7 bits if (mask7 & num == 128): #Check Sign (8th bit) num = -((~int(num) + 1) & mask2s) #2 complement return num 
0
source

Source: https://habr.com/ru/post/1485821/


All Articles