Printing floating point numbers in assembler

I am trying to print a floating point value from an assemler calling the printf function. It works great with strings and integer values, but does not print flotations. Here is an example of working code:

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 

Line: 255 ff .. end of line

So, the parameters are passed through registers: edi contains the address of the format string, rsi and rdx contain the same number for printing in decimal and hexadecimal styles, rcx contains the end of the line, rax contains 0, since we do not have a float for printing. This code works fine, but something changes when trying to print a 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 can be compiled, but returns a segmentation error that is being executed. It seems that the problem is in the wrong xmm0 value, but when you try to change movsd xmm0, [val] to movsd xmm0, val gives

error: invalid combination of opcode and operands

message. NASM compiler runs on openSuSe 12.3

Update I tried to create a c program and create a .S assembly. This gives a very strange solution:

 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 

Can I write a simple printf example?

+2
source share
1 answer

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

insert

 sub rsp, 8 

immediately after main:

then add it before ret:

 add rsp, 8 
+3
source

All Articles