从0学习汇编语言(6)包含多个段的程序

321 阅读2分钟

《从0学习汇编语言目录》

第六章 包含多个段的程序

6.1 在代码中使用数据

db: 定义数据,每个数据占一个byte 占一个字节 dw: 定义数据,每个数据占一个word 占两个字节 dd: 定义数据,每个数据占 double word 占4个字节

程序6.1

assume cs: code
code segment
dw 0123h,0456h,9abch,0efh,0fedh,0cbah,0987h 
start:  mov bx, 0
        mov ax, 0
        mov cx, 8
    s:  add ax, cs:[bx]
    	add bx,2
    	loop segment

    	mov ax,4c00h
    	int 21h
code ends
end start  ;表示在start中开始程序

该汇编程序是计算0123h,0456h,9abch,0efh,0fedh,0cbah,0987h的累加之和。

可以表示为如下所示

assume cs: code
code segment
        :
        数据
        :
start:  
        :
        代码
        :
code ends
end start  ;表示在start中开始程序

6.2 在代码段中使用栈

ss:sp指向栈底, sp为偏移量, 可以在汇编中使用 pushpop来操作一段数据

代码示例

assume cs: codesg
codesg segment
	dw 0123h,0456h,0789h,9abch,0efh,0fedh,0cbah,0987h 
	dw 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0   ;用作栈
start:
	 mov ax, cs
	 mov ss, ax
	 mov sp, 30h

	 mov bx, 0
	 mov cx, 8

	 s: push cs:[bx]  ;向栈内推数据
	 	add bx, 2
	 	loop s

	 	mov bx, 0
	 	mov cx, 8
	 s0:pop cs:[bx]   ;从栈取数据
	 	add bx, 2
	 	loop s0

	 	mov ax, 4c00h
	 	int 21h

codesg ends

end start

6.3 将数据、代码、栈放入不同的段

上面的代码显着比较乱,我们可以把不同的数据放到不同的段中,我们可以依据存放的数据类型,来添加不同的段,例如 数据段,栈段和代码段,如下面代码所示:

assume cs: code, ds:data, ss:stack

data segment
	dw 0123h,0456h,0789h,9abch,0efh,0fedh,0cbah,0987h 
data ends

stack segment
	dw 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0   ;用作栈
stack ends

code segment
start:
	 mov ax, stack
	 mov ss, ax
	 mov sp, 20h
	 
	 mov ax, data
	 mov ds, ax
	 
	 mov bx, 0
	 mov cx, 8

	 s: push [bx]  ;向栈内推数据 默认为ds:[bx]
	 	add bx, 2
	 	loop s

	 	mov bx, 0
	 	mov cx, 8
	 s0:pop [bx]   ;从栈取数据  默认为ds:[bx]
	 	add bx, 2
	 	loop s0

	 	mov ax, 4c00h
	 	int 21h

codesg ends

end start

对上述程序的说明:

  1. mov ax, stack 表示ax的值为stack段中的起始位置,会被标记为stack开始的一个数值

  2. 段地址的引用 mov ax, data mov ds, ax mov bx, ds:[6]

    我们不能用下面的命令 mov ds, data mov bx, ds:[6]

    其中mov ds, data 是错误的,因为8086不允许讲一个数值直接送到段寄存器中。

《从0学习汇编语言(7-8)更灵活的定位内存地址的方法 & 数据处理的两个基本问题》