1

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!

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Not sure this works with newer versions of NASM, as you can probably use something like %defstr
Off topic, but figured I'd ping you from here. In your Smaller-C - is there a way to force it to generate 8086 code only? I noticed some generated code had movzx. I may have missed the option in the docs although I only saw -seg16.
@MichaelPetch #include <sys/80186.h> is the closest you can get right now.
2

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.