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

前端 未结 5 1990
悲哀的现实
悲哀的现实 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:44

    This is code in abs.c in GNU glibc source code.

    /* Return the absolute value of I.  */
    int
    DEFUN(abs, (i), int i)
    {
      return(i < 0 ? -i : i);
    }
    

    So,abs(-2147483648) return -(-2147483648) . In x86,it is implement by this two instruction

    movl    $-2147483648, %eax
    negl    %eax
    

    negl instruction is implemented by this way: num=0-num; sbb is implemented by this way: Subtracts the source from the destination, and subtracts 1 extra if the Carry Flag is set. So abs(-2147483648) (hex is 0x80000000 ) --> -(-2147483648) --> 0-(-2147483648) becomes (0x80000000) finally.

    details of negl instruction,please visit http://zsmith.co/intel_n.html#neg

    details of sbb instruction ,please visit http://web.itu.edu.tr/kesgin/mul06/intel/instr/sbb.html

提交回复
热议问题