signed and unsigned arithmetic implementation on x86

前端 未结 3 872
[愿得一人]
[愿得一人] 2020-12-01 20:19

C language has signed and unsigned types like char and int. I am not sure, how it is implemented on assembly level, for example it seems to me that multiplication of signed

3条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-01 20:28

    A little supplement for cmp and sub. We know cmp is considered as non-destructive sub, so let's focus on sub.

    When a x86 cpu does a sub instruction, for example,

    sub eax, ebx
    

    How does the cpu know if either values of eax or ebx are signed or unsigned? For example, consider a 4 bit width number in two's complement:

    eax: 0b0001
    ebx: 0b1111
    

    In either signed or unsigned, value of eax will be interpreted as 1(dec), which is fine.

    However, if ebx is unsigned, it will be interpreted as 15(dec), result becomes:

    ebx:15(dec) - eax: 1(dec) = 14(dec) = 0b1110 (two's complement)
    

    If ebx is signed, then results becomes:

    ebx: -1(dec) - eax: 1(dec) = -2(dec) = 0b1110 (two's complement)
    

    Even though for both signed or unsigned, the encode of their results in two's complement are same: 0b1110.

    But one is positive: 14(dec), the other is negative: -2(dec), then comes back our question: how does the cpu tell which to which?

    The answer is the cpu will evaluate both, from: http://x86.renejeschke.de/html/file_module_x86_id_308.html

    It evaluates the result for both signed and unsigned integer operands and sets the OF and CF flags to indicate an overflow in the signed or unsigned result, respectively. The SF flag indicates the sign of the signed result.

    For this specific example, when the cpu sees the result: 0b1110, it will set the SF flag to 1, because it's -2(dec) if 0b1110 is interpreted as a negative number.

    Then it depends on the following instructions if they need to use the SF flag or simply ignore it.

提交回复
热议问题