Explain why x == ~(~x + 1) + 1 (two's complement and back!)

前端 未结 2 1707
醉话见心
醉话见心 2021-01-06 07:54

As we all know usually negative numbers in memory represents as two\'s complement numbers like that

from x to ~x + 1

and to get back we don

相关标签:
2条回答
  • 2021-01-06 08:01

    This is because if you increment ~x (assuming no overflow). Then converting it to back to x, you've incremented relative to ~x, but decremented relative to x. Same thing applies vice versa. Assuming your variable x has a specific value, every time you increment it, relative to ~x you'll notice it decrements.

    From a programmer's point of view, this is what you'd essentially witness.

    Let short int x = 1         (0x0001)
    then ~x = 65534             (0xFFFE)
    ~x + 1 =  65534 + 1         (0xFFFF)
    ~(~x+1) = 0                 (0x0000)
    ~(~x+1) + 1 = 0 + 1         (0x0001)
    
    0 讨论(0)
  • 2021-01-06 08:09

    That's the same thing anyway. That is, ~x + 1 == ~(x - 1). But let's put that aside for now.

    f(x) = ~x + 1 is its own inverse. Proof:

    ~(~x + 1) + 1 =
    (definition of subtraction: a - b = ~(~a + b))
    x - 1 + 1 =
    (you know this step)
    x
    

    Also, ~x + 1 == ~(x - 1). Why? Well,

    ~(x - 1) =
    (definition of subtraction: a - b = ~(~a + b))
    ~(~(~x + 1)) =
    (remove double negation)
    ~x + 1
    

    And that (slightly unusual) definition of subtraction, a - b = ~(~a + b)?

    ~(~a + b) =
    (use definition of two's complement, ~x = -x - 1)
    -(~a + b) - 1 =
    (move the 1)
    -(~a + b + 1) =
    (use definition of two's complement, ~x = -x - 1)
    -(-a + b) =
    (you know this step)
    a - b
    
    0 讨论(0)
提交回复
热议问题