'How to handle n=32 in fitsBits

working on an exercise from Computer Systems: A programmer's perspective and this is what i came up with. Unfortunatly this doesn't work in the case that n=32, if n=32 it doesn't shift x at all so it returns 1 regardless. This is a problem if x=0x80000000 because in this case it should return 0

/* 
 * 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 diff = 32 +(~n + 1);//diff between n and 32
  return !(x ^ ((x << diff) >> diff)); //shifts x left by diff then right by diff leaving the num unchanged if it would fit as an n-bit 2s comp int then xor's with x so it will be !0 if x matches shifted x or !1 otherwise
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source