I am trying REALLY hard to flip the bits in a C int variable. I am doing it like so:
input = 15;
input = ~input;
printf("%d", input);
BUT IT ALWAYS SHOWS UP as -16. It should be 0! if 15 is written as 1111, why is it returning 10000?! This is maddening! Can somebody PLEASE help me!?
Since
inton your system is most likely a 32-bit number, all bits are flipped, including the ones that were insignificant zeros in the original number:becomes
This is a negative number: the most significant bit of
15is zero, so it becomes1when flipped.If you would like to keep only the bits of the original number, you need to mask with all ones in the significant positions of the number, like this:
ANDing with0xF“cuts off” all bits except the last four.