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

15 投票
7 回答
5096 浏览
提问于 2025-04-11 09:14

我正在尝试解码Python中os.wait()函数的结果。根据Python的文档,这个函数返回的是一个元组,里面包含了进程的PID(进程ID)和退出状态的指示信息:

这个指示信息是一个16位的数字,低字节表示杀死进程的信号编号,高字节表示退出状态(如果信号编号为零的话);如果生成了核心文件,低字节的高位会被设置。

我该如何解码这个退出状态指示(它是一个整数),以获取高字节和低字节呢?具体来说,我该如何实现下面代码片段中使用的解码函数:

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

相关问题:

7 个回答

2

你可以使用 struct 模块把一个整数分解成一串无符号的字节。

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)

如果你把这个和 array 模块结合起来使用,就能更方便地做到这一点:

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

针对你的一般性问题,你可以使用位操作

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()
14

这个代码可以实现你想要的功能:

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

撰写回答