How does the bitwise complement operator (~ tilde) work?

后端 未结 15 1579
无人共我
无人共我 2020-11-22 07:46

Why is it that ~2 is equal to -3? How does ~ operator work?

15条回答
  •  醉梦人生
    2020-11-22 08:04


    The Bitwise complement operator(~) is a unary operator.

    It works as per the following methods

    First it converts the given decimal number to its corresponding binary value.That is in case of 2 it first convert 2 to 0000 0010 (to 8 bit binary number).

    Then it converts all the 1 in the number to 0,and all the zeros to 1;then the number will become 1111 1101.

    that is the 2's complement representation of -3.

    In order to find the unsigned value using complement,i.e. simply to convert 1111 1101 to decimal (=4294967293) we can simply use the %u during printing.

提交回复
热议问题