在汇编程序中打印浮点数

时间:2022-11-23 12:17:02

I'm trying to print a floating-point value from assemler calling a printf function. It works fine with strings and integer values but fails printing floats. Here is an example of working code:

我正在尝试从调用printf函数的汇编程序中打印浮点值。它适用于字符串和整数值,但不能打印浮点数。下面是一个工作代码的示例:

global  main
extern  printf

section .data
  message:    db      "String is: %d %x %s", 10, 0
  end_message:    db    ".. end of string", 0 

section .text
  main:
    mov eax, 0xff
    mov     edi, message
    movsxd rsi, eax
    mov rdx, 0xff
    mov rcx, end_message
    xor rax, rax
    call printf
    ret

String is: 255 ff .. end of string

字符串为:255 ff ..结束的字符串

So, the parameters are passed through registers: edi contains address of a formatting string, rsi and rdx contain the same number to print in decimal and hex styles, rcx contains end of a string, rax contains 0 as we do not have a float to print. This code works fine but something changes while trying to print float:

因此,参数是通过寄存器传递的:edi包含格式化字符串的地址,rsi和rdx包含相同的数字,以十进制和十六进制格式打印,rcx包含字符串的末尾,rax包含0,因为我们没有浮点数来打印。这段代码运行良好,但在尝试打印float时发生了一些变化:

global main

extern printf

section .data
    val: dq 123.456
    msg: db "Result is: %fl",10, 0

section .text
    main:
    mov rdi,msg
    movsd xmm0,[val]
    mov eax,1
    call printf

    mov rax, 0
    ret

This code snipped can be compiled but returns segmentation fault being executed. It seems that the problem is in wrong value of xmm0 but trying to change movsd xmm0,[val] to movsd xmm0,val gives an

可以编译此代码片段,但返回正在执行的分割错误。似乎这个问题在xmm0的值上是错误的,但是试图将movsd xmm0 [val]更改为movsd xmm0,val给出了一个

error: invalid combination of opcode and operands

错误:操作码和操作数的组合无效

message. The compiler is NASM running on openSuSe 12.3

消息。编译器是运行在openSuSe 12.3上的NASM

Update. I tried to make a c program and produce a .S assembly. It gives a very weird solution:

更新。我试着制作一个c程序并制作一个。s程序集。它给出了一个非常奇怪的解决方案:

main:
.LFB2:
    .cfi_startproc
    pushq   %rbp
    .cfi_def_cfa_offset 16
    .cfi_offset 6, -16
    movq    %rsp, %rbp
    .cfi_def_cfa_register 6
    subq    $32, %rsp
    movl    %edi, -4(%rbp)
    movq    %rsi, -16(%rbp)
    movq    val(%rip), %rax
    movq    %rax, -24(%rbp)
    movsd   -24(%rbp), %xmm0
    movl    $.LC0, %edi
    movl    $1, %eax
    call    printf
    movl    $0, %eax
    leave
    .cfi_def_cfa 7, 8
    ret

Is it possible to write a simple printf example?

是否可以编写一个简单的printf示例?

1 个解决方案

#1


3  

for your assembler problem: you need to align the stack before your main program starts.

对于汇编程序问题:您需要在主程序启动之前对堆栈进行对齐。

insert

插入

sub rsp, 8

right after main:

后主要:

then add it again before ret:

然后在ret之前再次添加:

add rsp, 8

#1


3  

for your assembler problem: you need to align the stack before your main program starts.

对于汇编程序问题:您需要在主程序启动之前对堆栈进行对齐。

insert

插入

sub rsp, 8

right after main:

后主要:

then add it again before ret:

然后在ret之前再次添加:

add rsp, 8