Bitwise operations and shifts

Scalahansolo picture Scalahansolo · Feb 9, 2013 · Viewed 12.5k times · Source

Im having some trouble understanding how and why this code works the way it does. My partner in this assignment finished this part and I cant get ahold of him to find out how and why this works. I've tried a few different things to understand it, but any help would be much appreciated. This code is using 2's complement and a 32-bit representation.

/* 
 * fitsBits - return 1 if x can be represented as an 
 *  n-bit, two's complement integer.
 *   1 <= n <= 32
 *   Examples: fitsBits(5,3) = 0, fitsBits(-4,3) = 1
 *   Legal ops: ! ~ & ^ | + << >>
 *   Max ops: 15
 *   Rating: 2
 */
int fitsBits(int x, int n) {
    int r, c;
    c = 33 + ~n;
    r = !(((x << c)>>c)^x);
    return r;
}

Answer

Code-Apprentice picture Code-Apprentice · Feb 9, 2013
c = 33 + ~n;

This calculates how many high order bits are remaining after using n low order bits.

((x << c)>>c

This fills the high order bits with the same value as the sign bit of x.

!(blah ^ x)

This is equivalent to

blah == x