Bit Twiddling in C - computes 2 times x or returns largest signed number

Viewed 301

I am writing a function that computes 2 times the parameter x, but if it overflows it should return the largest positive or negative signed number. The problem is I can only use ! ~ & ^ | + << >>. 32-bit integers are involved.

This is what I have so far:

int boundedMult(int x){
    int xSign = x>>31
    int y = x << 1; // Multiply by 2
    int signBit = y>>31; // Capture the signBit of the answer
    int shift = signBit; 
    shift |= shift<<1; // Make shift all 1 or 0 depending on the sign bit
    shift |= shift<<2;
    shift |= shift<<4;
    shift |= shift<<8;
    shift |= shift<<15;
    int answer = ~signBit<<31 | shift; // 01111... If signBit=1 and 1000... If signBit=0
}

Seems fine, right? I also can't use any constants outside of an unsigned byte (0-255) inclusive. I've tried so many approaches but I end up breaking one of these rules in all of them.

4 Answers
Related