EMU8086 Assembly: Output generates the total number of bits instead of 输出中0的数量

EMU8086 Assembly: Output generates the total number of bits instead of The number of 0s in the output

任务是获取十进制的用户输入,将其转换为 16 位的二进制,然后找出二进制输出中 0 的个数。 找出二进制文件的第一部分似乎工作正常,但第二部分我做错了什么?它显示的是总位数而不是 0。

示例:输入:3 输出:0000000000000011 0 的数量:14

include "emu8086.inc"
.model small
.stack 100h
.data
zeroes dw ?
.code
    ;First part, user input in decimal then generating the output in Binary, 16 bits. --Works FINE

    mov ax, @data
    mov ds, ax
    
    call scan_num
    printn
    
    print "The binary is: "
    
    mov bx, 16
    
    _loop:
    shl cx, 1
    jc bin_1
    
    putc '0'
    
    dec bx
    jnz _loop
    jmp exit
    
    bin_1:
    putc '1'
    
    dec bx
    jnz _loop
    
    
    ;Second part, finding out the number of 0 bits in the binary output
    mov cx, 16
    
    up:
    rol ax, 01h
    
    inc bx
    
    jmp next
    next:
    loop up
    mov zeroes, bx
    
    mov ax, bx 
    printn
    print "The number of 0s: "
    call print_num
     
    
exit:
    mov ah, 4ch
    int 21h
    
;define
define_print_num
define_print_num_uns
define_scan_num

想想这个

如果您输入的是偶数(0、2、4,...),那么您显示该数字的二进制表示的循环将在尝试第二部分之前退出程序! jmp exit 指令应该读作 jmp SecondPart.

除了 Peter Cordes 在评论中写的内容之外,我想补充一点,如果 scan_num 给了你 CX 寄存器中的号码并且您在第一个循环中将其剥离清楚,在第二个循环中没有更多要处理的内容。此外,在第二个循环中,您希望数字在 AX 中; scan_num 是否一次将其结果传送到 2 个寄存器???

现在是解决方案

如果第一个循环可以额外完成计算零的工作,为什么还要写第二个循环?
当您可以使用可用的通用寄存器时,您不需要 zeroes(基于内存的)变量。

        ...
        call  scan_num
        printn
        print "The binary is: "
        XOR   BP, BP     ; Clear counter
        mov   bx, 16
    _loop:
        shl   cx, 1
        jc    bin_1
    bin_0:
        INC   BP         ; Found an extra zero
        putc  '0'
        dec   bx
        jnz   _loop
        JMP   DONE
    bin_1:
        putc  '1'
        dec   bx
        jnz   _loop
    DONE:
        MOV   AX, BP
        printn
        print "The number of 0s: "
        call  print_num
    exit:
        ...

我已将更改大写,以便您可以轻松看到差异。