assembly - 我的汇编代码为字符串长度计算了一个额外的字节
问题描述
我编写了以下代码来读取文本并计算长度并报告它。为了保持代码简单,我假设字符串的长度小于 10 个字符。
我用于构建的代码是
nasm -f elf64 strlen.asm && ld strlen.o -o strlen && ./strlen
我有两个问题:
- 此代码编译为 64 位,而代码本身为 32 位。我应该应用哪些更改才能使此代码也成为 64 位?
- 为什么应用程序总是报告长度多出一个字节?从理论上讲,它不计算空终止。给定的文本是否包含
\x10
or\x13
?
section .text
global _start
_start:
; show prompt message
mov edx, 19 ; number of bytes to write - one for each letter plus 0Ah (line feed character)
mov ecx, txt_prompt ; move the memory address of our message string into ecx
mov ebx, 1 ; write to the STDOUT file
mov eax, 4 ; invoke SYS_WRITE (kernel opcode 4)
int 80h
; read the user input
mov eax, 3 ; Read user input into str
mov ebx, 0 ; |
mov ecx, user_input ; | <- destination
mov edx, 100 ; | <- length
int 80h ; \
; calculate the length
mov ebx, user_input ; move the address of our message string into EBX
mov eax, ebx ; move the address in EBX into EAX as well (Both now point to the same segment in memory)
strlen_nextchar:
cmp byte [eax], 0 ; compare the byte pointed to by EAX at this address against zero (Zero is an end of string delimiter)
jz strlen_finished ; jump (if the zero flagged has been set) to the point in the code labeled 'finished'
inc eax ; increment the address in EAX by one byte (if the zero flagged has NOT been set)
jmp strlen_nextchar ; jump to the point in the code labeled 'strlen_nextchar'
strlen_finished:
sub eax, ebx ; subtract the address in EBX from the address in EAX
add byte [txt_output+33], al
; show output message
mov edx, 34 ; number of bytes to write - one for each letter plus 0Ah (line feed character)
mov ecx, txt_output ; move the memory address of our message string into ecx
mov ebx, 1 ; write to the STDOUT file
mov eax, 4 ; invoke SYS_WRITE (kernel opcode 4)
int 80h
; exit code
mov ebx, 0
mov eax, 1
int 80h
section .data
txt_prompt: db 'Enter your message:', 0Ah
txt_output: db 'The string length is calculated: 0', 0Ah
section .bss
user_input: resb 100
解决方案
推荐阅读
- postgresql - 为什么索引会增加 postgres 中的执行时间?
- magento - 如何在magento 2后端保存盘点之前进行验证
- python-3.x - 获取python窗口中的空闲CPU计数
- c# - 以 xamarin 形式连接 3 个表
- java - 在Java流中处理时如何将列表细分为多个列表?
- c++ - 解决多个重载
- ignite - Apache Ignite Yarn 部署 HDFS 问题
- go - 为什么在 golang 中写入全局地图时恢复不起作用
- wordpress - 如果 post 存在且 post_meta 存在
- angular - 在 agm 上放置自定义控制按钮