~ operator in C

后端 未结 5 1441
星月不相逢
星月不相逢 2021-01-28 00:33

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?

<         


        
5条回答
  •  伪装坚强ぢ
    2021-01-28 01:13

    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;
    

提交回复
热议问题