我正在寻找一种在汇编语言中打印整数的方法(我使用的编译器是Linux上的NASM),但是在进行了一些研究后,我并没有找到一个真正可行的解决方案。我能够找到一个基本算法的描述来实现这个目的,并且根据这个算法,我开发了以下代码:
global _start
section .bss
digit: resb 16
count: resb 16
i: resb 16
section .data
section .text
_start:
mov dword[i], 108eh ; i = 4238
mov dword[count], 1
L01:
mov eax, dword[i]
cdq
mov ecx, 0Ah
div ecx
mov dword[digit], edx
add dword[digit], 30h ; add 48 to digit to make it an ASCII char
call write_digit
inc dword[count]
mov eax, dword[i]
cdq
mov ecx, 0Ah
div ecx
mov dword[i], eax
cmp dword[i], 0Ah
jg L01
add dword[i], 48 ; add 48 to i to make it an ASCII char
mov eax, 4 ; system call #4 = sys_write
mov ebx, 1 ; file descriptor 1 = stdout
mov ecx, i ; store *address* of i into ecx
mov edx, 16 ; byte size of 16
int 80h
jmp exit
exit:
mov eax, 01h ; exit()
xor ebx, ebx ; errno
int 80h
write_digit:
mov eax, 4 ; system call #4 = sys_write
mov ebx, 1 ; file descriptor 1 = stdout
mov ecx, digit ; store *address* of digit into ecx
mov edx, 16 ; byte size of 16
int 80h
ret
我想要实现的C#版本(为了更清晰):
static string int2string(int i)
{
Stack<char> stack = new Stack<char>();
string s = "";
do
{
stack.Push((char)((i % 10) + 48));
i = i / 10;
} while (i > 10);
stack.Push((char)(i + 48));
foreach (char c in stack)
{
s += c;
}
return s;
}
问题在于它以相反的顺序输出字符,因此对于
4238
,输出为8324
。起初,我认为我可以使用x86堆栈来解决这个问题,将数字推入堆栈中,在最后弹出并打印它们,然而当我尝试实现该功能时,它失败了,我无法得到输出。因此,我有点困惑如何将堆栈实现到该算法中,以完成我的目标,即打印一个整数。如果有更简单/更好的解决方案可用,我也会感兴趣(因为这是我的第一个汇编程序之一)。
stack.push()
)来防止人们意识到生成的代码实际上有多烂。注意:我敢你去反汇编那个C#生成的代码。。;-) - Brendan