The problem for signed 2's complement 32-bit integers:
satMul2
- multiplies by 2, saturating toTmin
orTmax
if overflow.
Examples:satMul2(0x30000000) = 0x60000000
satMul2(0x40000000) = 0x7FFFFFFF
(saturate toTMax
)
satMul2(0x60000000) = 0x80000000
(saturate toTMin
)
Legal ops:!
~
&
^
|
+
<<
>>
Max ops: 20
Rating: 3
I want to implement a function similar to
if (a) return b;
else return c;
This is my solution (10 ops):
int satMul2(int x) {
int rval = x << 1;
int sign = rval ^ x;
int minn = 1 << 31;
int temp = sign >> 31;
int flow = minn ^ (rval >> 31);
return ((~temp) & rval) | (temp & flow);
}
My professor told me there was a solution only 6 ops. Can someone please give me some hints?
Your solution has 2 instances of undefined behavior (one potential, one explicit) and 2 of explicit implementation defined behavior. Your professor would be well advised to teach about these instead of indulging in bogus challenges such as minimizing ops.
Here is a correct portable implementation:
As can be studied with Godbolt's Compiler Explorer, clang compiles this function to efficient branchless code: