Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using tilde to get MAX value for int

Tags:

c++

c

memory

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.

like image 642
Miro Avatar asked Mar 25 '11 21:03

Miro


3 Answers

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
like image 151
Carl Norum Avatar answered Oct 02 '22 13:10

Carl Norum


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

like image 26
Mark B Avatar answered Oct 02 '22 14:10

Mark B


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.

like image 29
Thomas Matthews Avatar answered Oct 02 '22 13:10

Thomas Matthews