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

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

    I think the way abs works is to first check the sign bit of the number. If its clear do nothing as the number is already +ve else return the 2's complement of the number. In your case the number is -ve and we need to find its 2's complement. But 2's complement of 0x80000000 happens to be 0x80000000 itself.

    0 讨论(0)
  • 2021-02-07 03:20

    For a 32bit datatype there is no expression of +2^31, because the biggest number is 2^31-1 ... read more about the two's complement ...

    0 讨论(0)
  • 2021-02-07 03:20

    This goes back to how numbers are stored.

    Negative numbers are stored using two's complement. The algorithm goes like ...

    Flip all the bits, then add 1.

    Using eight bit numbers for examples ...

    +0 = -0

    00000000 -> 11111111, 11111111 + 1 = 100000000

    (but due to limitation of bits, this becomes 00000000).

    AND...

    -128 [aka -(2^7)] equals -(-128)

    10000000 -> 01111111, 01111111 + 1 = 10000000

    Hope this helps.

    0 讨论(0)
提交回复
热议问题