How can I obtain the value of INT_MAX using only the bitwise operators, in C? I expected ~0 to be 1111111111 (complement of 1, so decimal -1) and ~0 >> 1 to be 0111111111, which would be max, but it’s still -1.
Why is that and how can I obtain the value of INT_MAX by using 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-4as you’d like for fast divisions by two.)