~ operator in C

后端 未结 5 1452
星月不相逢
星月不相逢 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:18

    (12)10 in binary is (1100)2

    The tilde is the bitwise complement operator which makes 1100 --> 0011. However if you working on a 32 bit platform actually what we get is:

    0000 0000 0000 0000 0000 0000 0000 1100
    

    Whose bitwise complement is:

    1111 1111 1111 1111 1111 1111 1111 0011
    |
    

    Now since the left most bit is for sign the number becomes negative. If you use unsigned int you will be able to understand better what is happening:

    unsigned int a = 12;
    a = ~a;
    

    Will give:

    1111 1111 1111 1111 1111 1111 1111 0011
    

    Which is 4294967283

提交回复
热议问题