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 -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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With