Why is abs(0x80000000) == 0x80000000?

前端 未结 9 1406
心在旅途
心在旅途 2021-02-07 02:51

I just started reading Hacker\'s Delight and it defines abs(-231) as -231. Why is that?

I tried printf(\"%x\", abs(0x80000000)) on a f

9条回答
  •  既然无缘
    2021-02-07 03:06

    Because integers are stored in memory as a two's complement binary number, the positive version of the minimum value overflows back to negative.

    That is to say (in .NET, but still applies):

    int.MaxValue + 1 == int.MinValue  // Due to overflow.
    

    And

    Math.Abs((long)int.MinValue) == (long)int.MaxValue + 1
    

提交回复
热议问题