convert ascii character to signed 8-bit integer python

▼魔方 西西 提交于 2019-12-07 05:58:04

问题


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


来源:https://stackoverflow.com/questions/17067813/convert-ascii-character-to-signed-8-bit-integer-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!