一直认为写代码是学习编程语言的最好方式。 但是因为汇编并不适合用来做大型的项目。所以这里找了100个c++的练习题用来学习汇编。
这里想想一个一个练习写下去,然后贴出来,和大家分享学习下。
本文所用到的ide为RadAsm, 所以汇编为win32汇编。helloword 见利用RadASM 写汇编程序
习题1:有1、2、3、4个数字,能组成多少个互不相同且无重复数字的三位数?都是多少?
写成c代码很简单:
void p1_fun()
{
for (int i = 1; i <= 4; ++i){
for (int j = 1; j <= 4; ++j){
for (int k = 1; k <=4; ++k){
if (i !=j && i !=k && j != k){
ostringstream stringStream;
stringStream<<i<<j<<k;
cout<<stringStream.str()<<",";
}
}
}
}
}
用汇编实现如下
Title: Hello world
;Author: sld6666666@gmail.com
;Data: 2012-11-29
;Description: Assemble hello world
.386 ;¸Ã³ÌÐò¶ÔCPUµÄ×îµÍÒªÇóÊÇintel 386
.model flat, stdcall ; ƽ̹ÄÚ´æÄ£ÐÍ£¬ stacll º¯Êýµ÷Ó÷½Ê½
.stack 4096 ;Õ»µÄ´óСΪ4096B
option casemap:none
;include Í·Îļþ£¬ Á¬½Ó¿â
include msvcrt.inc
includelib msvcrt.lib
.data ;Êý¾Ý¶Î
index_0 dd dword
index_1 dd dword
index_2 dd dword
szFmt db '%d%d%d', 0
entryFmt db ' ',0
.code
start:
mov index_0, 0
forProcess_0:
cmp index_0, 5
jge rtnProcess
inc index_0
mov index_1, 0
forProcess_1:
cmp index_1, 5
jge forProcess_0
inc index_1
mov index_2, 0
forProcess_2:
cmp index_2, 5
jge forProcess_1
inc index_2
mov eax, index_0
mov ebx, index_1
mov edx, index_2
cmp eax, ebx
je forProcess_2
cmp eax, edx
je forProcess_2
cmp ebx, edx
je forProcess_2
invoke crt_printf, addr szFmt,eax, ebx, edx
invoke crt_printf, addr entryFmt
jmp forProcess_2
rtnProcess:
ret
end start
解释下几个关键点:
1. 输出函数利用了 msvcrt 中的printf
2. 导入库的关键字为includelib, 头文件的关键字为 include, 如include msvcrt.inc,includelib msvcrt.lib
3. 使用导入函数的关键字为 invoke
运行结果如下: