如何在Python中将整数视为字节数组?

时间:2020-03-05 18:39:26  来源:igfitidea点击:

我正在尝试解码Python os.wait()函数的结果。根据Python文档,这将返回:

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.

如何解码退出状态指示(整数)以获得高字节和低字节?具体来说,如何实现以下代码段中使用的解码功能:

(pid,status) = os.wait()
(exitstatus, signum) = decode(status)

解决方案

回答

这将做我们想要的:

signum = status & 0xff
exitstatus = (status & 0xff00) >> 8

回答

我们可以使用移位和掩码运算符解压缩状态。

low = status & 0x00FF
high = (status & 0xFF00) >> 8

我不是Python程序员,所以我希望语法正确。

回答

在我之前的人们已经对此进行了详细说明,但是如果我们确实希望将其固定在一行上,则可以执行以下操作:

(signum, exitstatus) = (status & 0xFF, (status >> 8) & 0xFF)

编辑:有倒退。

回答

要回答一般问题,我们可以使用位操作技术:

pid, status = os.wait()
exitstatus, signum = status & 0xFF, (status & 0xFF00) >> 8

但是,还有内置函数可用于解释退出状态值:

pid, status = os.wait()
exitstatus, signum = os.WEXITSTATUS( status ), os.WTERMSIG( status )

也可以看看:

  • os.WCOREDUMP()
  • os.WIFCONTINUED()
  • os.WIFSTOPPED()
  • os.WIFSIGNALED()
  • os.WIFEXITED()
  • os.WSTOPSIG()

回答

我们可以使用struct模块将int分解为无符号字节的字符串:

import struct
i = 3235830701  # 0xC0DEDBAD
s = struct.pack(">L", i)  # ">" = Big-endian, "<" = Little-endian
print s         # '\xc0\xde\xdb\xad'
print s[0]      # '\xc0'
print ord(s[0]) # 192 (which is 0xC0)

如果将其与数组模块结合使用,则可以更方便地执行此操作:

import struct
i = 3235830701  # 0xC0DEDBAD
s = struct.pack(">L", i)  # ">" = Big-endian, "<" = Little-endian

import array
a = array.array("B")  # B: Unsigned bytes
a.fromstring(s)
print a   # array('B', [192, 222, 219, 173])

回答

exitstatus, signum= divmod(status, 256)