Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

I'm trying to decode the result of the Python os.wait() function. This returns, according to the Python docs:

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.

How do I decode the exit status indication (which is an integer) to obtain the high and low byte? To be specific, how do I implement the decode function used in the following code snippet:

(pid,status) = os.wait()
(exitstatus, signum) = decode(status) 
like image 582
Lorin Hochstein Avatar asked Aug 13 '08 17:08

Lorin Hochstein


People also ask

How to convert int to bytes in Python?

You can use the int class method int.to_bytes () to convert an int object to an array of bytes representing that integer. The following is the syntax – length – The number of bytes to use to represent the integer. If the integer is not representable with the given number of bytes, an OverflowError is raised.

What is a ByteArray in Python?

A bytearray in python is an array of bytes that can hold data in a machine readable format. When any data is saved in the secondary storage, it is encoded according to a certain type of encoding such as ASCII, UTF-8 and UTF-16 for strings, PNG, JPG and JPEG for images and mp3 and wav for audio files and is turned into a byte object.

What is bytes () method in Python?

Python | bytes() method. Interconversion between different data types is provided by python language with ease. This article aims at demonstration and working of an interconversion of different data types to bytes(), usually useful for encoding schemes. byte() converts an object to immutable byte represented object of given size and data.

How many bytes are in a Unicode array Python?

UTF-8 is capable of encoding all 1,112,064 valid character code points in Unicode using one to four one-byte code units In this example, we are going to see how to get an array of bytes from an integer using the Python bytes () function, for this we will pass the integer into the bytes () function.


1 Answers

This will do what you want:

signum = status & 0xff
exitstatus = (status & 0xff00) >> 8
like image 123
Mark Harrison Avatar answered Sep 19 '22 02:09

Mark Harrison