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

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

    The representation of a two's complement number has the most significant bit as a negative number. 0x80000000 is 1 followed by 31 zeroes, the first 1 represents -2^31 not 2^31. Therefore there is no way to represent 2^31 as the highest positive number is 0x7FFFFFFF, which is 0 followed by 31 ones, which equals 2^31-1.

    abs(0x80000000) is therefore undefined in the two's complement since it is too large, due to this the machine just gives up and gives you 0x80000000 again. Typically at least.

提交回复
热议问题