Twos complement means that simply inverting all bits of a number i gets me -i-1:
~0 is -1
~01000001 is 10111110
~65 is -66
etc. To switch the sign of an integer, I have to use the actual minus sign.
int i = 65; int j = -i;
cout << j; // -65
Where is that actual behavior defined, and whose responsibility is it to ensure the twos complement pattern (to make a number negative invert all bits and add 1) is followed? I don't even know if this is a hardware or compiler operation.
It's usually done by the CPU hardware.
Some CPUs have an instruction for calculating the negative of a number. In the x86 architecture, it's the
NEG
instruction.If not, it can be done using the multiplication operator, multiplying the number by
-1
. But many programmers take advantage of the identity that you discovered, and complement the number and then add 1. SeeHow to convert a positive number to negative in assembly