下面是從Python source code中看來的一個檢驗兩個long整數相加是否回overflow的方法。
// 傳回0表示無overflow,反之,傳回1表示overflow.
int addc(long a, long b, long *result)
{
*result = a + b;
// 用XOR來檢查結果與被加數或加數是否有正負號交換的現象。
if ((*result ^ a) >= 0 || (*result ^ b) >= 0)
{
return 0; // no overflow.
}
return 1; // overflow.
}
No comments:
Post a Comment