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

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

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

15条回答
  •  失恋的感觉
    2020-11-22 08:16

    Simply ...........

    As 2's complement of any number we can calculate by inverting all 1s to 0's and vice-versa than we add 1 to it..

    Here N= ~N produce results -(N+1) always. Because system store data in form of 2's complement which means it stores ~N like this.

      ~N = -(~(~N)+1) =-(N+1). 
    

    For example::

      N = 10  = 1010
      Than ~N  = 0101
      so ~(~N) = 1010
      so ~(~N) +1 = 1011 
    

    Now point is from where Minus comes. My opinion is suppose we have 32 bit register which means 2^31 -1 bit involved in operation and to rest one bit which change in earlier computation(complement) stored as sign bit which is 1 usually. And we get result as ~10 = -11.

    ~(-11) =10 ;

    The above is true if printf("%d",~0); we get result: -1;

    But printf("%u",~0) than result: 4294967295 on 32 bit machine.

提交回复
热议问题