Orby
Orby

Reputation: 207

Nasm: Convert integer to string using preprocessor

How does one convert an integer to a string using the Nasm preprocessor? For example, consider the following code:

%define myInt 65
%define myString 'Sixty-five is ', myInt

The symbol myString will evaluate to Sixty-five is A. The desired result is Sixty-five is 65. How can I achieve this? It seems like such a trivial question, but the Nasm documentation has yielded nothing. Thanks!

Upvotes: 1

Views: 1581

Answers (3)

Stepan
Stepan

Reputation: 46

You should use %defstr macro.

%define myInt 65
%defstr strInt myInt
%define myString 'Sixty-five is ', strInt

https://www.nasm.us/xdoc/2.15.05/html/nasmdoc4.html#section-4.1.9

Upvotes: 2

Alexey Frunze
Alexey Frunze

Reputation: 62048

This code

%define myInt 65
%define quot "
%define stringify(x) quot %+ x %+ quot
%strcat myString 'Sixty-five is ', stringify(myInt)

bits 32
db myString

produces the following listing file:

 1                                  %define myInt 65
 2                                  %define quot "
 3                                  %define stringify(x) quot %+ x %+ quot
 4                                  %strcat myString 'Sixty-five is ', stringify(myInt)
 5                                  
 6                                  bits 32
 7 00000000 53697874792D666976-     db myString
 8 00000009 65206973203635     

and the following binary:

0000000000: 53 69 78 74 79 2D 66 69 │ 76 65 20 69 73 20 36 35  Sixty-five is 65

I used NASM version 2.10 compiled on Mar 12 2012.

Upvotes: 3

nrz
nrz

Reputation: 10550

At the moment can't test this with NASM, but this works at least in YASM (I added a Linux x86-64 printing code to make testing easier):

[bits 64]

%define myInt 65
%define myTens myInt/10 + 48
%define myOnes myInt-(myInt/10)*10 + 48
%define myString 'Sixty-five is ', myTens, myOnes

section .text
global _start

_start:
    mov edi,1   ; STDOUT        
    mov rsi,my_string
    mov edx,my_string_length    ; length of string in bytes.
    mov eax,1   ; write
    syscall

    xor edi,edi
    mov eax,60  ; exit
    syscall

section .data
my_string db myString
db 0x0a
my_string_length equ $-my_string

Upvotes: 0

Related Questions