2012-06-15 43 views
1

我用使用os.system運行make命令的16位字節的最高位轉換爲符號整型在Python

os.system('make -C mydir/project all') 

我想看看如果make失敗與否。該系統文檔指出的返回碼是相同的格式爲wait()

Wait for completion of a child process, and return 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. 

因此,如果化妝(或其他應用程序)返回-1,我不得不0xFFxx轉換(我真的不關心的PID被調用)爲-1。右移後,我得到0xFF,但我不能得到它轉換爲-1,它總是打印255.

所以,在Python中,我怎麼能將255轉換爲-1,或者我怎麼能告訴解釋器,我的255實際上是一個8位有符號整數?

+1

什麼系統你是在使用簽名的返回狀態? (GNU make應該永遠不會返回0,1或2以外的值)。 – geoffspear

回答

3

雖然伊格納西奧的答案可能對於這種情況會更好,從特殊格式的數據拆包字節一個很好的通用工具struct

>>> val = (255 << 8) + 13 
>>> struct.unpack('bb', struct.pack('H', val)) 
(13, -1) 
+0

這並不像使用'numpy.int8'那麼糟糕,但它仍然是不必要的工作。 –

7
if number > 127: 
    number -= 256 
相關問題