In: Computer Science
unsigned u =10;
int i = -42;
cout << i+i <<endl;
cout << u+i<<endl;//if int take 32 bit, output
4294967264
I know when unsigned and singed operate together, they need to be converted, but why is the answer 4294967264? What does it have to do with int .…… 32 bit
-42 in stored in memory using 2's complement This is negative. so, follow these steps to convert this into a 2's complement binary Step 1: Divide 42 successively by 2 until the quotient is 0 > 42/2 = 21, remainder is 0 > 21/2 = 10, remainder is 1 > 10/2 = 5, remainder is 0 > 5/2 = 2, remainder is 1 > 2/2 = 1, remainder is 0 > 1/2 = 0, remainder is 1 Read remainders from the bottom to top as 101010 So, 42 of decimal is 101010 in binary Adding 26 zeros on left hand side of this number to make this of length 32 So, 42 in normal binary is 00000000000000000000000000101010 Step 2: flip all the bits. Flip all 0's to 1 and all 1's to 0. 00000000000000000000000000101010 is flipped to 11111111111111111111111111010101 Step 3:. Add 1 to above result 11111111111111111111111111010101 + 1 = 11111111111111111111111111010110 so, -42 in 2's complement binary is 11111111111111111111111111010110 unsigned value of 11111111111111111111111111010110 is => 11111111111111111111111111010110 => 1x2^31+1x2^30+1x2^29+1x2^28+1x2^27+1x2^26+1x2^25+1x2^24+1x2^23+1x2^22+1x2^21+1x2^20+1x2^19+1x2^18+1x2^17+1x2^16+1x2^15+1x2^14+1x2^13+1x2^12+1x2^11+1x2^10+1x2^9+1x2^8+1x2^7+1x2^6+0x2^5+1x2^4+0x2^3+1x2^2+1x2^1+0x2^0 => 1x2147483648+1x1073741824+1x536870912+1x268435456+1x134217728+1x67108864+1x33554432+1x16777216+1x8388608+1x4194304+1x2097152+1x1048576+1x524288+1x262144+1x131072+1x65536+1x32768+1x16384+1x8192+1x4096+1x2048+1x1024+1x512+1x256+1x128+1x64+0x32+1x16+0x8+1x4+1x2+0x1 => 2147483648+1073741824+536870912+268435456+134217728+67108864+33554432+16777216+8388608+4194304+2097152+1048576+524288+262144+131072+65536+32768+16384+8192+4096+2048+1024+512+256+128+64+0+16+0+4+2+0 => 4294967254 so, u + i = 10 + 4294967254 = 4294967264