【问题标题】:Convert highest byte of 16-bits to signed int in python在python中将16位的最高字节转换为带符号的int
【发布时间】:2012-06-15 19:12:31
【问题描述】:

我使用 os.system 来运行 make 命令

os.system('make -C mydir/project all')

我想看看 make 是否失败。系统文档说明返回码与wait()格式相同

Wait for completion of a child process, and return a tuple containing its pid 
and exit status indication: a 16-bit number, whose low byte is the signal number 
that killed the process, and whose high byte is the exit status (if the signal 
number is zero); the high bit of the low byte is set if a core file was produced.

所以如果make(或其他应用程序)返回-1,我必须将0xFFxx(我并不关心被调用的pid)转换为-1。右移后,我得到 0xFF,但我无法将其转换为 -1,它总是打印 255。

那么,在 python 中,我如何将 255 转换为 -1,或者如何告诉解释器我的 255 实际上是一个 8 位有符号整数?

【问题讨论】:

  • 您在哪个系统上使用签名返回状态? (GNU make 永远不应返回 0、1 或 2 以外的值)。

标签: python type-conversion bit-shift


【解决方案1】:
if number > 127:
  number -= 256

【讨论】:

  • 当输入是有符号整数并且 OP 只是右移时,为什么按位运算给出无符号数的任何解释?
【解决方案2】:

虽然 Ignacio 的回答可能更适合这种情况,但从特殊格式的数据中解包字节的良好通用工具是 struct

>>> val = (255 << 8) + 13
>>> struct.unpack('bb', struct.pack('H', val))
(13, -1)

【讨论】:

  • 虽然没有numpy.int8那么糟糕,但它仍然比必要的工作多。
猜你喜欢
  • 2013-02-18
  • 1970-01-01
  • 2013-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-03
相关资源
最近更新 更多