Error with Tilde Bitwise Operator

Let's examine the code.

int x = 100;
unsigned long answer1 = ~x;
unsigned long long answer2 = ~x;


cout << (bitset<32>) x << "\n";
cout << (bitset<32>) answer1 << "\n";
cout << (bitset<32>) answer2 << "\n";
cout << x << "\n" << answer1 << "\n" << answer2 << "\n";

Shouldn't the decimal of answer 1 and 2 the same thing?
I get 4294967195 for answer1
and 18446744073709551515 for answer 2.

I'm lost.
int x = 100; In this case ~x is a negative number. When you assigning negative value V to unsigned number, result is equal to maximum possible value for corresponding unsigned data type + 1 - V.

Standard wrote:
4.7.2
If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (modulo 2^n where n is the number of bits used to represent the unsigned type). [ Note: In a two’s complement representation, this conversion is conceptual and there is no change in the bit pattern (if there is no truncation). —end note ]
Last edited on
Topic archived. No new replies allowed.