簡體   English   中英

如何在裝配中使用浮點數進行操作?

[英]How can I operate with float point numbers in assembly?

我需要從C發送兩個實數( 使用extern'C'double(double num1,double num2 ))到返回這些數字相加的匯編過程 我還不知道該怎么做。

我試過了,但是沒有用。

.data

 res dq 0

.code

        procSuma proc num1,num2

           fld num1   ; load num1 and push it onto the fpu stack
           fld num2   ; load num2 and push it onto the fpu stack
           faddp      ; pop two numbers, add them, push sum on the stack
           fstp res   ; pop sum from the stack and store it in res

        procSuma endp
 end

出問題的地方是將原本不包含在函數中的粘貼代碼復制到函數中,我相信您是從這里得到的。 在程序集中添加浮點數/雙數

由於匯編代碼現在包含在proc中,因此不再需要變量來存儲結果,因為結果存儲在堆棧中st(0)的地址處,該地址就是您的返回值。 調用fstp ,它將彈出堆棧(提示:末尾的p),因此存儲在st(0)處的返回值不再有效。 刪除fstp指令將為您提供預期的結果。

這就是代碼的逐步操作。

procSuma proc num1,num2   

       fld num1   ; This pushes num1 onto the stack at the address of st(0)
       fld num2   ; This pushes num2 onto the stack at the address of st(1)
       faddp      ; This multiplies st(1) and st(0), stores the result at st(0), and then pops the variable stored at st(1) off the stack   
       fstp res   ; !REMOVE THIS. This is why you aren't getting the expected result.It pops the variable in st(0) off the stack, which is your return value.

procSuma endp

我假設這是一項家庭作業,需要您使用x87 FPU指令。 或者,您可以使用SSE / SSE2 SIMD指令執行添加。

Win32上的C調用( cdecl )約定要求在ST(0) (在FPU堆棧頂部的寄存器)中返回單精度和雙精度浮點數。 由於faddp將兩個數字相加並將結果放在ST(0)中,這意味着我們不需要任何臨時變量來存儲結果。 這些行可以刪除

.data
res dq 0

fstp res   ; pop sum from the stack and store it in res

創建過程時,應指定要傳遞的參數的大小,以便MASM確切知道操作數用於操作的大小。 為確保使用雙精度值,請將參數標記為REAL8(8字節REALS)。 您還應該將PROC標記為與PROC C一起使用C調用約定,以便正確設置和解決堆棧和參數。 過程聲明應類似於:

procSuma proc C num1:REAL8,num2:REAL8 

結果代碼如下所示:

.model flat, c
.code

        procSuma proc C num1:REAL8,num2:REAL8

           fld num1   ; load num1 and push it onto the fpu stack
           fld num2   ; load num2 and push it onto the fpu stack
           faddp      ; pop two numbers, add them, push sum on the stack.
                      ; result in st(0) (top of FPU stack)
                      ; We return double values in st(0) so nothing to do
                      ; since faddp put our result in st(0)
           ret

        procSuma endp
 end

您可以使用FADD代替FADDP來減少一些說明中的添加內容

       fld num1   ; load num1 and push it onto the fpu stack
       fadd num2  ; Add ST(0)(num1) to num2 and store result in ST(0).
                  ; We return double values in st(0) so nothing to do
                  ; since fadd put our result in st(0)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM