【问题标题】:Using db to declare a string in assembly NASM使用 db 在程序集 NASM 中声明一个字符串
【发布时间】:2017-05-29 14:07:27
【问题描述】:

我正在按照教程编写一个用汇编语言编写的 hello world 引导加载程序,并且我正在将 NASM 汇编程序用于 x-86 机器。这是我正在使用的代码:

[BITS 16]   ;Tells the assembler that its a 16 bit code
[ORG 0x7C00]    ;Origin, tell the assembler that where the code will
            ;be in memory after it is been loaded

MOV SI, HelloString ;Store string pointer to SI
CALL PrintString    ;Call print string procedure
JMP $       ;Infinite loop, hang it here.


PrintCharacter: ;Procedure to print character on screen
;Assume that ASCII value is in register AL
MOV AH, 0x0E    ;Tell BIOS that we need to print one charater on screen.
MOV BH, 0x00    ;Page no.
MOV BL, 0x07    ;Text attribute 0x07 is lightgrey font on black background

INT 0x10    ;Call video interrupt
RET     ;Return to calling procedure



PrintString:    ;Procedure to print string on screen
;Assume that string starting pointer is in register SI

next_character: ;Lable to fetch next character from string
MOV AL, [SI]    ;Get a byte from string and store in AL register
INC SI      ;Increment SI pointer
OR AL, AL   ;Check if value in AL is zero (end of string)
JZ exit_function ;If end then return
CALL PrintCharacter ;Else print the character which is in AL register
JMP next_character  ;Fetch next character from string
exit_function:  ;End label
RET     ;Return from procedure


;Data
HelloString db 'Hello World', 0 ;HelloWorld string ending with 0

TIMES 510 - ($ - $$) db 0   ;Fill the rest of sector with 0
DW 0xAA55           ;Add boot signature at the end of bootloader

我很难理解如何使用 db 命令将完整的“Hello World”字符串放入一个字节中。据我了解,db 代表 define byte 并将所述字节直接放在可执行文件中,但“Hello World”肯定大于一个字节。我在这里错过了什么?

【问题讨论】:

  • 当字符串出现在db 中时,该字符串会自动分解为每个单独的字符并存储在连续的字节中。 HelloString db 'Hello World', 0 被拆分并被视为HelloString db 'H','e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', 0
  • 相关,更详细的dwdd 字符串:How are dw and dd different from db directives for strings?

标签: string assembly x86 nasm bootloader


【解决方案1】:

伪指令dbdwdd和朋友can define multiple items

db 34h             ;Define byte 34h
db 34h, 12h        ;Define bytes 34h and 12h (i.e. word 1234h)

它们也接受字符常量

db 'H', 'e', 'l', 'l', 'o', 0

但是这种语法对于字符串来说很笨拙,所以接下来的逻辑步骤是给出明确的支持

db "Hello", 0         ;Equivalent of the above

附:一般来说prefer the user-level directives,虽然对于[BITS][ORG]是无关紧要的。

【讨论】:

  • message: db 'hello, world!', 10 我不清楚单个变量message 过去如何在字符串“hello world”中存储这么多独立的字节(使message 像高级语言中的数组一样.
  • @ThangNguyen 变量只是地址的名称(或者,在程序加载到内存之前,用于偏移量/位置计数器)。所以在message: db "hello, world!", 10 中,message 是第一个db 元素的地址名称(在本例中为h)。所有其他元素都在h 之后按顺序排列,当然,它们也占用空间。所以效果就像message 是一个字符/字节数组。但实际上,汇编中没有类型,每个变量都可以充当(或不能充当)数组。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-21
  • 1970-01-01
  • 1970-01-01
  • 2015-10-06
  • 2015-12-04
相关资源
最近更新 更多