Search code examples
assemblypreprocessornasm

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!


Solution

  • 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.