标签:style blog os sp 2014 log ad amp as
#include<limits.h> int saturating_add(int x,int y) { int sum = x + y; <span style="white-space:pre"> </span>int w = sizeof(int) << 3; int x_sign = x >> (w - 1); // 取出x的符号位 int y_sign = y >> (w - 1); // 取出y的符号位 int sum_sign = sum >> (w - 1);//取出sum的符号位 int pos_overflow = x_sign && y_sign && !sum; //判断正溢 int neg_overflow = !x_sign && !y_sign && sum;//判断负溢 int overflow = pos_overflow || neg_overflow;//设置溢出位 overflow <<= w - 1; overflow >>= w - 1; //将溢出位设置为全0 或 全 1 int result = (sum & ~overflow ) + ((INT_MAX + !pos_overflow) & overflow); //根据是否溢出进行二路选择 INT_MAX = 0x7fffffff(32位机器) INT_MAX + 1 = 0X80000000 = INT_MIN return result; }
标签:style blog os sp 2014 log ad amp as
原文地址:http://blog.csdn.net/u012769069/article/details/41845045