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

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

一个包含其pid和退出状态指示的元组:一个16位数字,其低字节是杀死该进程的信号号,其高字节是退出状态(如果信号号为零);如果生成了核心文件,则设置低字节的高位。

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

(pid,status) = os.wait()

(exitstatus, signum) = decode(status) 


白板的微信
浏览 216回答 3
3回答

胡子哥哥

这将做您想要的:signum = status & 0xffexitstatus = (status & 0xff00) >> 8

肥皂起泡泡

要回答您的一般问题,您可以使用位操作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 structi = 3235830701&nbsp; # 0xC0DEDBADs = struct.pack(">L", i)&nbsp; # ">" = Big-endian, "<" = Little-endianprint s&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;# '\xc0\xde\xdb\xad'print s[0]&nbsp; &nbsp; &nbsp; # '\xc0'print ord(s[0]) # 192 (which is 0xC0)如果将其与数组模块结合使用,则可以更方便地执行此操作:import structi = 3235830701&nbsp; # 0xC0DEDBADs = struct.pack(">L", i)&nbsp; # ">" = Big-endian, "<" = Little-endianimport arraya = array.array("B")&nbsp; # B: Unsigned bytesa.fromstring(s)print a&nbsp; &nbsp;# array('B', [192, 222, 219, 173])
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python