Get INT_MAX with bit operations

Try ~0UL >> 1. The issue is that C will do a sign-extended right shift if it's dealing with a signed type. This is why you're still getting negative one -- because it's shifting in another 1 bit to match the 1 bit that was there. (That way -8 >> 1 gives -4 as you'd like for fast divisions by two.)


If you shift a negative number to the right, the new bits of the number may be 1 (to keep it negative). That why you get -1.

Edit: You can do something like:

int i=1;
while (i<<1) i<<=1;
i=~i;

If you treat 0 as an unsigned integer, the compiler will not perform a signed shift:

int i = ~0U >> 1;

This will give you INT_MAX