Get INT_MAX with bit operations

How can I get the value of INT_MAX using only bitwise operators in C? I expected that ~0 would be 1111111111 (addition to 1 , so decimal -1 ) and ~0 >> 1 would be 0111111111 , which would be max, but it was still -1 .

Why is this and how can I get the value of INT_MAX using INT_MAX operations?

+4
source share
6 answers

Try ~0UL >> 1 . The problem is that C will make a shift with the sign extension if it deals with a signed type. That's why you still get a negative result - because it has moved another 1 bit to match the 1 bit that was there. (In this case, -8 β†’ 1 gives -4 , as you want fast divisions by two.)

+9
source

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

Edit: you can do something like:

 int i=1; while (i<<1) i<<=1; i=~i; 
+2
source

If you treat 0 as an unsigned integer, the compiler will not shift with the signature:

 int i = ~0U >> 1; 

This will give you INT_MAX

+2
source

As far as I know, there is no portable solution other than using the INT_MAX macro. See my old question:

Programmatically determining the maximum value of a signed integer type

and the question on which it is based:

Question C: off_t (and other signed integer types) minimum and maximum values

+1
source

(1 <31) -1)

. This is an old thread, but I will still send it to all who destroy it. But this is not entirely bitwise, and it is assumed that the "int" on your computer is 32bit.

+1
source
 #include <stdio.h> int main(){ int max = ~0U >> 1; int min = ~max; printf("Max = 0x%X, min = 0x%X", max, min); return 0; } 

Output:

 Max = 0x7FFFFFFF, min = 0x80000000 
0
source

Source: https://habr.com/ru/post/1397884/


All Articles