I am currently learning the process of bitwise operators, and I've come across something that I can't quite figure out.
Im currently working with the NOT(~) operator, which should invert all of the bits. So in order to get a better understanding of it, I've tried creating a program that will flip the number 1's bits.
int main()
{
int x = 1; // 0001 in binary
int y = ~x; // should flip the bits, so its 1110, or 14
cout << y;
}
However, when running this, i am getting -2 as the result. Can anyone offer an explanation as to why this isn't working?
You're using signed integers. Your expected result (14) would occur if you were using unsigned integers (and if the integer were only 4 bits, which it is not).
Instead, with signed integers, all values with the highest bit set are negative values - that's how Two's Complement works. For example, if you have 16 bits, then values
0b0000_0000_0000_0000through0b0111_1111_1111_1111are assigned to the positive values ("0" through "32767") meanwhile values0b1000_0000_0000_0000through0b1111_1111_1111_1111are assigned to the negative values ("-32768" through "-1").Also,
intusually is more than 4 bits; it's often 32-bits. The negation of 1 would be0b1111_1111_1111_1111_1111_1111_1111_1110, not0b1110.0b1111_1111_1111_1111_1111_1111_1111_1110when treated as a signed integer is-2using the Two's Complement rules.0b1111_1111_1111_1111_1111_1111_1111_1110when treated as an unsigned integer is4,294,967,294, equal to2^32 - 2.