我一直致力于将一些代码从 MASM 格式转换为 NASM 格式以进行汇编。然而,我在这两方面都没有受过很好的教育,而且我一直遇到问题。我几乎不理解 NASM,因此尝试转换代码非常困难。如果有人可以转换它并解释他们如何从 MASM 转换为 NASM,那将非常有用。另外,如果有任何现代的转换工具,那也会很有帮助。
我的主要问题似乎是 .DATA 部分和偏移变量。根据我的研究,NASM 没有“抵消”,但我对如何正确地替代它感到困惑。 我使用 dosbox 进行编译。
.MODEL SMALL
.STACK 100H
.DATA
msg db 10, 13, "Enter a three-digit number: $"
buffer db 4 DUP ('$') ; Buffer to store the input
result db 10, 13, "Binary value: $"
.CODE
main PROC
mov ax, @data
mov ds, ax
lea dx, msg
mov ah, 09h ; Display prompt
int 21h
mov dx, offset buffer ; Load pointer to the buffer
mov ah, 0Ah ; Read input
int 21h ; Convert ASCII input to binary
xor cx, cx ; Initialize counter
mov cl, buffer[1] ; Get the length of input
mov si, offset buffer + 2 ; Point to the actual input
; Loop to convert ASCII digits to binary
convert_loop:
mov al, [si]
sub al, '0' ; Convert ASCII to numeric value
shl al, cl ; Shift left based on position
or dl, al ; Combine with result
dec cl ; Decrement counter
inc si ; Move to next digit
loop convert_loop ; Display the binary value
lea dx, result
mov ah, 09h ; Display result prompt
int 21h ; Print binary value
mov ah, 02h ; Print character
mov dl, '0' ; Initialize with '0'
print_loop:
shl dl, 1 ; Shift left
rcl dh, 1 ; Rotate carry into high byte
int 21h
loop print_loop
mov ah, 4Ch ; Exit program
int 21h
main ENDP
END main
这个程序中的错误太多了:
提示“输入三位数:”不明确。它没有明确说明需要一个二进制数字,并且对于正确操作是必需的。
正如 @ecm 在评论中所写,buffer (
buffer db 4 DUP ('$')
) 的定义对于 DOS.BufferedInput 函数 0Ah 使用不正确。
在convert_loop中,结果会累积在事先未设置的寄存器中。
在convert_loop中,“根据位置向左移动”向左移动了 1 位。
在convert_loop中,“递减计数器”扰乱了CX循环控制变量,使循环运行时间过长。请记住,CL 是 CX 的低字节。
在print_loop中,‘左移’和‘循环进位到高字节’都是无意义操作。
print_loop不会初始化其循环控制变量。您忘记在 CX 寄存器中移动合适的值。
消息“二进制值:”不明确。目前尚不清楚是否需要print_loop。输入 3 个二进制数字可以产生 [0,7] 范围内的结果,并且 that 您可以通过单次调用 DOS.PrintCharacter 函数 02h 来显示。
下面是改进后的代码。它仍然是为 MASM 编写的,但是有了 @Jester 在评论中提供的 NASM 手册的链接,您是否能够轻松地将其转换为 NASM?
ORG 256
mov dx, offset msg
mov ah, 09h
int 21h
mov dx, offset buffer
mov ah, 0Ah
int 21h
mov bl, 0 ; Result
mov cl, buffer[1] ; Expected to contain a value in [1,3]
mov si, offset buffer + 2
convert_loop:
mov al, [si]
inc si
sub al, '0'
dec cl
shl al, cl ; Shift left based on position
or bl, al ; Combine with result
test cl, cl
jnz convert_loop
mov dx, offset result
mov ah, 09h
int 21h
mov dl, '0'
add dl, bl ; BL=[0,7]
mov ah, 02h
int 21h
mov ax, 4C00h
int 21h
; ----------------------------
msg db 13, 10, "Enter a three-digit binary number: $"
result db 10, "Binary value: $"
buffer db 4, 0, 4 dup (0)
额外提示:NASM 不会喜欢mov cl,buffer[1]
。每个地址部分都属于方括号之间。使用加号字符进行连接。