Removing bit at specific index
As explained in the comments, the shift counts rolled over to >= 32, which caused trouble.
Anyway, let's derive a way to do it.
Start by considering the two "pieces", the low piece (which gets copied in its original position and may be anywhere between 0 .. 31 bits long) and the high piece (which gets shifted down by one, and can also be between 0 .. 31 bits long). The total length of the pieces is always 31.
The mask for the low piece is obvious: ~(-1 << i)
Which makes the mask for the high piece obvious: ~lowmask << 1
. The high piece is shifted anyway, so that shift can go.
Now all that's left is to take the pieces and OR them together, and you would get
static int removeBit(int x, int i)
{
int mask = ~(-1 << i);
return (x & mask) | ((x >>> 1) & ~mask);
}
Throw out the double negation:
static int removeBit(int x, int i)
{
int mask = -1 << i;
return (x & ~mask) | ((x >>> 1) & mask);
}