I tryed to get MAX value for int, using tilde.But output is not what I have expected. When I run this:
#include <stdio.h>
#include <limits.h>
int main(){
    int a=0;
    a=~a;
    printf("\nMax value: %d",-a);
    printf("\nMax value: %d",INT_MAX);
    return 0;
}
I get output:
Max value: 1
Max value: 2147483647
I thought,(for exemple) if i have 0000 in RAM (i know that first bit shows is number pozitiv or negativ).After ~ 0000 => 1111 and after -(1111) => 0111 ,that I would get MAX value.
You have a 32-bit two's complement system.  So - a = 0 is straightforward.  ~a is 0xffffffff. In a 32-bit two's complement representation, 0xffffffff is -1.   Basic algebra explains that -(-1) is 1, so that's where your first printout comes from.  INT_MAX is 0x7fffffff.
Your logical error is in this statement:  "-(1111) => 0111", which is not true.  The arithmetic negation operation for a two's complement number is equivalent to ~x+1 - for your example:
~x + 1 = ~(0xffffffff) + 1
       = 0x00000000 + 1
       = 0x00000001
                        Is there a reason you can't use std::numeric_limits<int>::max()? Much easier and impossible to make simple mistakes.
In your case, assuming 32 bit int:
int a = 0;   // a = 0
a = ~a;      // a = 0xffffffff = -1 in any twos-comp system
a = -a;      // a = 1
So that math is an incorrect way of computer the max. I can't see a formulaic way to compute the max: Just use numeric_limits (or INT_MAX if you're in a C-only codebase).
Your trick of using '~' to get maximum value works with unsigned integers. As others have pointed out, it doesn't work for signed integers.
Your posting shows an int which is equivalent to signed int.  Try changing the type to unsigned int and see what happens.
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