6.1 在代码段中使用数据
我们来看一个程序:
assume cs:code
code segment
dw 0123h,0456h,0789h,0abch,0defh,0fedh,0cbah,0987h
start: mov bx, 0
mov ax, 0
mov cx, 8
s: add ax, cs:[bx]
add bx, 2
loop s
mov ax, 4c00h
int 21h
code ends
end start
代码中的dw的含义是定义字符数据。dw即define word,这段代码中,使用dw定义了8个字型数据,一共占据16个字节。程序运行时,这8个数据的地址分别是CS:0,CS:2…CS:E。
使用dw等方式存放数据,在代码段开头标记start,并在end后写上start,表面第一条指令。
6.2 在代码段中使用栈
看一个程序
assume cs:codesg
codesg segment
dw 0123h,0456h,0789h,0abch,0defh,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,0abch,0defh,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]
add bx, 2
loop s
mov bx, 0
mov cx, 8
s0: pop [bx]
add bx, 2
loop s0
mov ax, 4c00h
int 21h
code ends
end start
定义多个段,不同的段有不同的名字。段名代表了段地址,使用时只需写偏移地址。“代码段”“数据段”“栈段”完全是我们的安排,名字没有数据意义,只需方便编程起。