Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get INT_MAX with bit operations

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?

like image 804
Paul Manta Avatar asked Feb 22 '12 20:02

Paul Manta


2 Answers

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.)

like image 92
Kaganar Avatar answered Oct 13 '22 12:10

Kaganar


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;
like image 31
asaelr Avatar answered Oct 13 '22 13:10

asaelr