【问题标题】:Nasm: Convert integer to string using preprocessorNasm:使用预处理器将整数转换为字符串
【发布时间】:2013-03-17 00:40:15
【问题描述】:

如何使用 Nasm 预处理器将整数转换为字符串?例如,考虑以下代码:

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

符号myString 将计算为Sixty-five is A。所需的结果是Sixty-five is 65。我怎样才能做到这一点?这似乎是一个微不足道的问题,但 Nasm 文档却一无所获。谢谢!

【问题讨论】:

    标签: assembly preprocessor nasm


    【解决方案1】:

    这段代码

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

    生成以下列表文件:

     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     
    

    以及以下二进制文件:

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

    我使用的是 2012 年 3 月 12 日编译的 NASM 版本 2.10。

    【讨论】:

    • 不确定这是否适用于较新版本的 NASM,因为您可能可以使用类似 %defstr
    • 离题,但我想我会从这里 ping 你。在您的 Smaller-C 中 - 有没有办法强制它只生成 8086 代码?我注意到一些生成的代码有movzx。虽然我只看到了-seg16,但我可能错过了文档中的选项。
    • @MichaelPetch #include <sys/80186.h> 是您现在可以得到的最接近的。
    【解决方案2】:

    你应该使用 %defstr 宏。

    %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

    【讨论】:

      【解决方案3】:

      目前无法使用 NASM 进行测试,但这至少在 YASM 中有效(我添加了 Linux x86-64 打印代码以使测试更容易):

      [位 64] % 定义 myInt 65 %define myTens myInt/10 + 48 %define myOnes myInt-(myInt/10)*10 + 48 %define myString '六十五是', myTens, myOnes 部分 .text 全局_start _开始: 移动编辑,1;标准输出 mov rsi,my_string mov edx,my_string_length ;字符串的长度(以字节为单位)。 移动 eax,1 ;写 系统调用 xor edi,edi 移动 eax,60 ;出口 系统调用 节 .data 我的字符串数据库我的字符串 数据库 0x0a my_string_length equ $-my_string

      【讨论】:

        猜你喜欢
        • 2017-09-16
        • 1970-01-01
        • 2010-09-19
        • 1970-01-01
        • 2011-01-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多