【问题标题】:assembly reading binary number to decimal 8086 (NASM)汇编读取二进制数到十进制 8086 (NASM)
【发布时间】:2013-04-10 21:53:42
【问题描述】:

我不明白我做错了什么。我需要二进制计算器,其输入格式类似于“00000001b+00000010b ...输出也需要为二进制... 运算符可以是 +、-、*、/。

我想读取第一个数字并将其转换为十进制......我的代码是这样的

%include "asm_io.inc"

segment .text
    global _asm_main
_asm_main:
    enter 0,0
    pusha


    call read_int
    cmp al,'b'
    je vypis

vypis:
    call print_int


koniec:
    popa                 ; terminate program
    mov EAX, 0
    leave
    ret

当输入以数字 1 开头时,程序运行良好,例如 (10101010b),但当输入以 0 开头时,它就不能正常工作...

我的问题是我做错了什么或者我怎样才能做得更好?


print_int 和 read_int 是已经提供给我们的函数,它们可以 100% 工作... 我可以使用的其他函数是 read_char、print_char 和 print_string ...

read_int:
    enter   4,0
    pusha
    pushf

    lea eax, [ebp-4]
    push    eax
    push    dword int_format
    call    _scanf
    pop ecx
    pop ecx

    popf
    popa
    mov eax, [ebp-4]
    leave
    ret

print_int:
    enter   0,0
    pusha
    pushf

    push    eax
    push    dword int_format
    call    _printf
    pop ecx
    pop ecx

    popf
    popa
    leave
    ret

【问题讨论】:

    标签: assembly x86 nasm x86-16


    【解决方案1】:

    在我看来read_int 只是返回一个整数值(在eax 中),它已被scanf 读取。我不确定为什么您希望该整数的最低有效字节为'b'(?)。

    虽然我不知道您使用的是哪个scanf 实现,但我还没有看到任何可以直接读取二进制数的实现。不过,自己实现该功能相当容易。
    下面是一些展示原理的 C 示例代码:

    char bin[32];
    unsigned int i, value;
    
    scanf("%[01b]", bin);  // Stop reading if anything but these characters
                           // are entered.
    
    value = 0;
    for (i = 0; i < strlen(bin); i++) {
        if (bin[i] == 'b')
            break;
        value = (value << 1) + bin[i] - '0';
    }
    // This last check is optional depending on the behavior you want. It sets
    // the value to zero if no ending 'b' was found in the input string.
    if (i == strlen(bin)) {
        value = 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-06
      • 2012-04-02
      • 1970-01-01
      • 2015-05-29
      • 1970-01-01
      • 2016-01-10
      • 2014-03-24
      • 1970-01-01
      相关资源
      最近更新 更多