The output of this program is -13. I have never fully understood ~ operator in C. Why does it give -13 as output? How to limit ~ operator to just 4 bits of a number?
<
The operator ~
is the logical not
in C, i.e. when applied to a integer it flips every single it of its binary representation. Note that defining a integer in simply as int
makes it unsigned integer. That means that the first it is used as a sign bit. Since negatives are defines as -a = ~a + 1
you can see that ~a = -a - 1
. If you want to flip only the last 4(or more generally the last k) bit of a int
you could do something like this
int k = 4;
int mask = (1 << k) - 1;
int b = a ^ mask;