Question: Need help understanding the code below, comments next to lines of code explaining whats happending and why. /* * satMul3 - multiplies by 3, saturating
Need help understanding the code below, comments next to lines of code explaining whats happending and why.
/* * satMul3 - multiplies by 3, saturating to Tmin or Tmax if overflow * Examples: satMul3(0x10000000) = 0x30000000 * satMul3(0x30000000) = 0x7FFFFFFF (Saturate to TMax) * satMul3(0x70000000) = 0x7FFFFFFF (Saturate to TMax) * satMul3(0xD0000000) = 0x80000000 (Saturate to TMin) * satMul3(0xA0000000) = 0x80000000 (Saturate to TMin) * Legal ops: ! ~ & ^ | + << >> * Max ops: 25 * Rating: 3 */ int satMul3(int x) { int x_sign_mask = x >> 31; int x_sign = x_sign_mask & 1; int mul2 = x + x; int mul2_sign = (mul2 >> 31) & 1; int mul3 = mul2 + x; int mul3_sign = (mul3 >> 31) & 1; int overflow = (x_sign ^ mul2_sign) | (mul2_sign ^ mul3_sign); int overflow_mask = (overflow << 31) >> 31; int overflow_candidate = (~x_sign_mask) ^ (0x01 << 31); return (overflow_mask & overflow_candidate) | ((~overflow_mask) & mul3); }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
