http://teaching.idallen.com/dat2343/10f/notes/040_overflow.txt
英文不好,所以每次回去看時又要花時間,直接把重點翻成中文,之後覆習比較快。
In unsigned arithmetic, watch the carry flag to detect errors. In unsigned arithmetic, the overflow flag tells you nothing interesting. In signed arithmetic, watch the overflow flag to detect errors. In signed arithmetic, the carry flag tells you nothing interesting.
算數運算(ALU)中,偵測運算結果是否正確。
無號數 (unsigned) 運算,只看進位𣄃標(carry flag),不看溢位𣄃標 (overflow flow)
有號數 (signed) 運算, 只看溢位𣄃標 (overflow flow), 不看進位𣄃標(carry flag)
[無號數運算]
運算超過表示位元,以下面為例,是以 4bits 或相加相減。
加法
1111 + 0001 = 0000 (產生進位,進位𣄃標被設定)
減法 (借位, 還是以進位𣄃標 carry flag 表示) 0000 - 0001 = 1111 (產生借位,進位𣄃標被設定
其他情況
0111 + 0001 = 1000 (CF=0) 1000 - 0001 = 0111 (CF=0)
[有號數運算]
有號數採用二進位補數系統做運算,正或負數會看MSB是0或1。
0100 + 0100 = 1000 (正+正=負, OF=1) 1000 + 1000 = 0000 (負+負=正, OF=1)
其他情況
0100 + 0001 = 0101 (OF=0) 0110 + 1001 = 1111 (OF=0) 1000 + 0001 = 1001 (OF=0) 1100 + 1100 = 1000 (OF=0)
計算溢位的方式1
使用二數值的 MSB (sign bit) 及加, 減運算後的結果 MSB (Sign bit) 做判斷
加法
A B S = A+B=S
0 0 0
*OVER* 0 0 1 (正+正=負, OF=1)
0 1 0
0 1 1
1 0 0
1 0 1
*OVER* 1 1 0 (負+負=正, OF=1)
1 1 1
減法
A B S = A+B=S
0 0 0
0 0 1
0 1 0
*OVER* 0 1 1 (正-(負)=正-(-正)=正+正=負, 負負得正OF=1)
*OVER* 1 0 0 (負-正=正, 己經是負數,又再多減,會更負, 但結果為正是錯的,所以 OF=1)
1 0 1
1 1 0
1 1 1
計算溢位的方式2
https://www.electronics-tutorials.ws/binary/signed-binary-numbers.html
使用進位機制做判斷, 以 2bit 為例, carry in 為 bit 0, carry out bit 1
當二個 magnitude bits 運算後,有進位到 sign bit,但沒出去 -> carry out 到 bit 9
當二個 magnitude bits 運算後,沒進位到 sign bit,但有出去 -> carry out 到 bit 9
都會產生溢位。
11
+01
===
00
- carry in is 1
- carry out is 1
- 1 XOR 1 = NO OVERFLOW
01
+01
===
10
- carry in is 1
- carry out is 0
- 1 XOR 0 = OVERFLOW!
11
+10
===
01
- carry in is 0
- carry out is 1
- 0 XOR 1 = OVERFLOW!
10
+01
===
11
- carry in is 0
- carry out is 0
- 0 XOR 0 = NO OVERFLOW
