For faster navigation, this Iframe is preloading the Wikiwand page for
算術溢出.
算術溢位(arithmetic overflow)或簡稱為溢位(overflow)指的是:
- 在電腦領域裡所發生的溢位條件是,執行單項數值計算時,當計算產生出來的結果是非常大的,大於暫存器或記憶體所能儲存或表示的能力限制。
- 在電腦領域裡,執行多項或累計的數值計算時,當計算產生出來的總值是非常大的,大於暫存器或記憶體所能儲存或表示的能力限制。要注意的是,溢位可能會在其他位址被置換。[來源請求]
加法器是中央处理器算术逻辑单元中的核心之一。当长度为n位的两个二进制数经过加减法器运算,得到的长度为n位的结果不是正确值时,我们说发生溢出。
檢查溢位
大多數的電腦都可以區別以上兩種溢位條件。當加法或減法的結果發生進位,必須考量到當運算的數值與結果都是unsigned numbers(無號數值,即「正數」)型態時,運算的結果就不適合使用這個數值型態。所以,在執行無號數值(正數)的加法或減法之後檢查進位旗標是非常有用的作法。「溢位」在運算結果為無號數值時容易發生,可以從有符號的運算數值預計出這類的情形(例如:兩個正整數相加產生的結果為一個負數)。所以,在執行2的補數的加法或減法之後檢查溢位旗標是非常有用的作法(換言之,有考慮到有號數值)。
控制溢位
有幾個控制溢位的方法:
- 設計:選擇正確的資料型態,尤其要注意資料長度與signed/unsigned資料符號。
- 迴避:事先注意指令的運作以及檢查運算的數值,或許可以確保計算出來的結果不會超過記憶體儲存資料的限制。
- 控制:當它被偵測到,還有在其他的程序完成時被檢測出來,那麼溢位是可以被預料的。例如:兩個位元大的兩個數值做加法計算,這種情形最可能發生。步驟如下:先加低位元再加高位元,但是如果它必須完成低位元的運算,就會產生位元加法的運算溢位,那麼就有必要做偵測和增加高位元的總和。通常CPU有支援偵測數值加法大於暫存器大小的作法,基本上這個作法是採用狀態位元的方式。
- 增值:假如儲存的數值過大就會被分配給其他特定的數值,這時溢位就會發生,然後傳回旗標值時就會產生連續運作的現象。檢查這個問題最有用的方法,就是在整體的計算結尾做一次性的檢查工作,而不是檢查每一個執行步驟。這個作法最常用在浮點硬體呼叫浮點運算器。
- 忽略:這是最普遍的作法,但是這個作法會得出不正確的結果,以及降低程式的安全性。
除零計算
任何數除以零的計算(Divided by zero)「不是」算術溢位的一種。在數學上只能明顯算是不明確的定義(Undefined);它計算出來的結果只能當成是「沒有」值,而不是非常大的無限數值。
{{bottomLinkPreText}}
{{bottomLinkText}}
This page is based on a Wikipedia article written by
contributors (read/edit).
Text is available under the
CC BY-SA 4.0 license; additional terms may apply.
Images, videos and audio are available under their respective licenses.
{{current.index+1}} of {{items.length}}
Thanks for reporting this video!
This browser is not supported by Wikiwand :(
Wikiwand requires a browser with modern capabilities in order to provide you with the best reading experience.
Please download and use one of the following browsers:
An extension you use may be preventing Wikiwand articles from loading properly.
If you're using HTTPS Everywhere or you're unable to access any article on Wikiwand, please consider switching to HTTPS (https://www.wikiwand.com).
An extension you use may be preventing Wikiwand articles from loading properly.
If you are using an Ad-Blocker, it might have mistakenly blocked our content.
You will need to temporarily disable your Ad-blocker to view this page.
✕
This article was just edited, click to reload
Please click Add in the dialog above
Please click Allow in the top-left corner,
then click Install Now in the dialog
Please click Open in the download dialog,
then click Install
Please click the "Downloads" icon in the Safari toolbar, open the first download in the list,
then click Install
{{::$root.activation.text}}
Follow Us
Don't forget to rate us
Oh no, there's been an error
Please help us solve this error by emailing us at
support@wikiwand.com
Let us know what you've done that caused this error, what browser you're using, and whether you have any special extensions/add-ons installed.
Thank you!