How do I treat an integer as an array of bytes in Python?

To answer your general question, you can use bit manipulation

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

However, there are also built-in functions for interpreting exit status values:

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

See also:

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

You can get break your int into a string of unsigned bytes with the struct module:

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)

If you couple this with the array module you can do this more conveniently:

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

This will do what you want:

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

Tags:

Python