int saturating_add(int x, int y)
{
int nbit = sizeof(int) << 3;
int result = x + y;
/* `of' means overflow.It will be 111...11111 if overflowed,0000...000 otherwise */
int of = ( ( x ^ result ) & ( y ^ result ) ) >> nbit - 1;
/* `sign' = 111...111 if sign of x is -,
000...000 otherwise */
int sign = x >> nbit - 1;
/**
set result to 0111111111 if `of' == 111...111,
then turn them off if sign == 111...111,make it INT_MIN;
if not overflow,return result.
***/
return (result | of) - (( 1 << nbit - 1) & of ) ^ ( sign & of);
}
编写函数,当正溢出时,返回TMax,负溢出时,返回TMin。
最新推荐文章于 2023-04-06 13:45:39 发布