Using bitwise operators multiply an integer by 3, but return max if overflow

0

This is for a homework problem I am currently stuck on. I have to multiply an integer by 3, if there if overflow return the maximum (0x7FFFFFFF) and underflow return the minimum (0x80000000). I am using 32bit numbers and am restricted to only using the operators: ! ~ & ^ | + << >>

I feel as though I have solved it, but when I run the professors tests the case x = 0x7FFFFFFF incorrectly returns 0x7FFFFFFd. There could be other tests failing, but that is the first one that fails and it doesn't run the other tests.

This is my code so far:

int satMul3(int x) {
    int threex = x + x + x; //Definition of multiplication 3x = x+x+x
    int signx = x >> 31; //Makes bit all same number as MSB (1s = neg 0s = pos)
    int sign3 = threex >> 31; //Same as signx but for the result of x*3
    int overflow = signx ^ sign3; //Checks if signs are same. 0s if same sign
    int tmin = 0x80000000;
    int tmax = 0x7FFFFFFF;
    int answer = (sign3 & tmin) | (~sign3 & tmax);
    //Gets answer for overflow, if sign3 is negative returns Tmin else tmax

    return (overflow & answer) | (~overflow & threex); //If overflow is 1,
    //signs are the same so return x*3, if overflow is 0, then signs are
    //different so return the saturated answer
}

Hopefully it is just a simple error, but if not any advice would be greatly appreciated.

c
bit-manipulation
bitwise-operators
asked on Stack Overflow Mar 21, 2018 by Henry • edited Mar 21, 2018 by Henry

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0