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

前端 未结 9 1423
心在旅途
心在旅途 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:10

    0x8000.. is stored as 10000.... (binary). This is known as twos complement, which means that the highest bit (the one at the left) is used to store the sign of the value and negative values are stored with negative binary - 1. The abs() function now checks the signbit, sees that it is set and computes the positive value.

    • To get the positive value it first negates all bits in the variable, resulting in 01111...
    • Then adds 1, which again results in 1000... the 0x8000... we started with

    Now this is a negative number again which we didn't want, the reason is a overflow, try the number 0x9000... which is 10010...

    • negating the bits results in 01101... adding one results in 01110...
    • which is 0xE000...a positive number

    With this number the overflow is stopped by the 0 bit on the right

提交回复
热议问题