convert ascii character to signed 8-bit integer py

2019-05-05 23:35发布

问题:

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.

回答1:

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]


回答2:

Use this function to get a signed 8bit 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's complement
    return num


回答3:

from ctypes import c_int8
value = c_int8(191).value

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

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 16bit integer representation of hex 'BF' and value2 is 8bit representation



回答4:

I know this is an old question, but I haven't found a satisfying answer elsewhere.

You can use the array module (with the extra convenience that it converts complete buffers):

from array import array

buf = b'\x00\x01\xff\xfe'
print(array('b', buf))

# result: array('b', [0, 1, -1, -2])