samedi 20 janvier 2018

How are operations on a long integer interpreted in c++?

              #include<iostream>
              using namespace std;

              int main()
              {
               int t;
               cin>>t;
               while(t--)
               {
                   int x=32;
                   long long n;
                   long long t=1;
                   cin>>n;
                   while(x--)
                   {
                      n=(n^t);
                      t=t<<1;
                   }
                   cout<<n<<endl;
               }
               return 0;
              }

Input 3 2147483647 1 0

Output 2147483648 4294967294 4294967295

The above code inverts the number and interprets the result as an unsigned integer. Why so? Shouldn't the resultant numbers be negative? Further if I use just the negation operator (~) on the number n, in place of the while loop, the result printed is negative.

Output -2147483648 -2 -1

When the above operations are performed, aren't the binary representation of the numbers the same? Why is it being interpreted differently? Unsigned in the first case and signed in the second? The result produced remains the same when long long is replaced by long.

Can someone explain to me how this works?

Aucun commentaire:

Enregistrer un commentaire