/* 2.73 Addition that saturates to TMin or TMax Your function should follow the bit-level integer coding rules */intsaturating_add(intx, inty){
intsum=x+y;
intbits=sizeofx << 3;
intxmsb=x >> (bits-1)
, ymsb=y >> (bits-1)
, smsb=sum >> (bits-1);
intp_o= !xmsb& !ymsb&smsb;
intn_o=xmsb&ymsb& !smsb;
intno_o= !p_o& !n_o;
return (p_o&TMAX) | (n_o&TMIN) | (no_o&sum);
}
use >>, << to replace loop
/*Return 1 when x contains an odd number of 1s; 0 otherwise.Assume w=32.GET:1. xor keep 1's number still odd/even2. bit manipulate can work like following recusive way.*/intodd_ones(unsignedx) {
x=x ^ (x >> 16);
x=x ^ (x >> 8);
x=x ^ (x >> 4);
x=x ^ (x >> 2);
x=x ^ (x >> 1);
returnx;
}
test special case: INT_MIN, 0
characteristic of Integer: non-symetric, may overflow