會有人請還跟我感謝你解釋一下這個功能!需要幫助瞭解整數運算功能
int overflow(int x, int y)
{
int result, non_overflow, overflow, result_sign, mask;
result = x + y;
result_sign = result >> 31; //Need help starting from here... I know
//it is shifting 31 bits... but why??
non_overflow = ((x^y) | ~(y^result)) >> 31;
overflow = ~non_overflow;
mask = overflow << 31;
return (non_overflow & result) | (overflow & (result_sign^mask));
}
你有沒有拍過兩對數字(一個是在添加時溢出,一個是沒有的),然後通過手動或者在調試器中通過算法來看*每個操作發生了什麼? – WhozCraig
沒有想到這一點。謝謝。順便說一句..你怎麼讓它溢出? – juice
最簡單的方法? '溢出(MAX_INT,MAX_INT)'應該這樣做。但是,這一切都需要在32位''平臺上運行,否則無論如何這都不起作用。看起來你已經從標籤中知道,但是。 – WhozCraig