Why the absolute value of the max negative integer -2147483648 is still -2147483648?

前端 未结 5 1992
悲哀的现实
悲哀的现实 2020-12-03 05:14

The result of abs(-2147483648) is -2147483648, isn\'t it? it seems unacceptable.

printf(\"abs(-2147483648): %d\\n\", abs(-2147483648));

out

5条回答
  •  鱼传尺愫
    2020-12-03 05:39

    Negative numbers are usually represented whit binary complement.

    To convert positive to negative it is used logic

    x -> not(x)+1
    

    For 8 bits arithmetic

    01111111b is 127 and -127 becomes
    10000000b + 1 = 10000001b

    and to opposite direction -127 10000001b becomes
    01111110b + 1 = 01111111b

    What about -128?

    -128 is 10000000b and there is no positive counterpart of it, because there is no 128 in 8 bits signed arithmetic.

    10000000 -> 01111111 + 1 = 10000000 and -128 again

    Same applies to original question

提交回复
热议问题