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 .
INT_MAX
~0
1111111111
1
-1
~0 >> 1
0111111111
Why is this and how can I get the value of INT_MAX using INT_MAX operations?
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.)
~0UL >> 1
-8
-4
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;
If you treat 0 as an unsigned integer, the compiler will not shift with the signature:
0
int i = ~0U >> 1;
This will give you INT_MAX
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 <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.
#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
Source: https://habr.com/ru/post/1397884/More articles:Ajax.ActionLink does not trigger controller action - c #Minimalistic real-time mapping in Python - python(C ++) How can I pause the main thread and then resume another thread in it? - c ++Reliable way to get machine wake up + user registered in Cocoa notification? - objective-cHow to minimize data warehouse records initiated by mapreduce library? - pythonChecking for email in the database? - phpCan you indicate if the vertex attribute of the vertex shader is enabled? - openglSynchronizing iPhone Audio and Sound Queue Services - iosUsing the Apache Commons configuration to interpolate variables, that is $ {variable}, with a list of values ββin the properties file - javaHow to access stdout or stderr in Capybara integration test - ruby-on-railsAll Articles