将ascii字符转换为带符号的8位整数python [英] convert ascii character to signed 8-bit integer python
本文介绍了将ascii字符转换为带符号的8位整数python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这感觉应该很简单,但我找不到答案..
This feels like it should be very simple, but I haven't been able to find an answer..
在python脚本中我正在读取数据USB设备(USB鼠标的x和y移动)。它以单个ASCII字符到达。我可以使用ord轻松转换为无符号整数(0-255)。但是,我希望它是签名整数(-128到127) - 我该怎么做?
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.
推荐答案
如果超过127则减去256:
Subtract 256 if over 127:
unsigned = ord(character)
signed = unsigned - 256 if unsigned > 127 else unsigned
或者,使用 struct $ c重新打包字节$ c>模块:
from struct import pack, unpack
signed = unpack('B', pack('b', unsigned))[0]
或直接来自角色:
signed = unpack('B', character)[0]
这篇关于将ascii字符转换为带符号的8位整数python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文