-11

What is the difference between ~i and INT_MAX^i Both give the same no. in binary but when we print the no. the output is different as shown in the code below

#include <bits/stdc++.h>
using namespace std;
void binary(int x)
{
int i=30;
while(i>=0)
{
    if(x&(1<<i))
      cout<<'1';
    else
      cout<<'0';
    i--;  
}
cout<<endl;
}
int main() {
  int i=31;
  int j=INT_MAX;
  int k=j^i;
  int g=~i;
  binary(j);
  binary(i);
  binary(k);
  binary(g);
  cout<<k<<endl<<g;
 return 0;
}

I get the output as

1111111111111111111111111111111
0000000000000000000000000011111
1111111111111111111111111100000
1111111111111111111111111100000  
2147483616
-32

Why are k and g different?

6 Answers6

7

K and g are different - the most significant bit is different. You do not display it since you show only 31 bits. In k the most significant bit is 0 (as the result of XOR of two 0's). In g it is 1 as the result of negation of 0 (the most significant bit of i).

Wojtek Surowka
  • 20,535
  • 4
  • 44
  • 51
3

Your test is flawed. If you output all of the integer's bits, you'll see that the values are not the same.

You'll also now see that NOT and XOR are not the same operation.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
2

Try setting i = 31 in your binary function; it is not printing the whole number. You will then see that k and g are not the same; g has the 'negative' flag (1) on the end.

Integers use the 32nd bit to indicate if the number is positive or negative. You are only printing 31 bits.

~ is bitwise NOT; ~11100 = ~00011 ^ is bitwise XOR, or true if only one or the other

André Peña
  • 163
  • 3
1

~ is bitwise NOT, it will flip all the bits

Example

 a:  010101
~a:  101010

^ is XOR, it means that a bit will be 1 iff one bit is 0 and the other is 1, otherwise it will set to 0.

  a: 010101
  b: 001100
a^b: 011001
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
0

You want UINT_MAX. And you want to use unsigned int's INT_MAX only does not have the signed bit set. ~ will flip all the bits, but ^ will leave the sign bit alone because it is not set in INT_MAX.

Robert Jacobs
  • 3,266
  • 1
  • 20
  • 30
0

This statement is false:

~i and INT_MAX^i ... Both give the same no. in binary

The reason it appears that they give the same number in binary is because you printed out only 31 of the 32 bits of each number. You did not print the sign bit.

The sign bit of INT_MAX is 0 (indicating a positive signed integer) and is is not changed during INT_MAX^i because the sign bit of i also is 0, and the XOR of two zeros is 0.

The sign bit of ~i is 1 because the sign bit of i was 0 and the ~ operation flipped it.

If you printed all 32 bits you would see this difference in the binary output.

David K
  • 3,147
  • 2
  • 13
  • 19