首页 > 解决方案 > 我的汇编代码为字符串长度计算了一个额外的字节

问题描述

我编写了以下代码来读取文本并计算长度并报告它。为了保持代码简单,我假设字符串的长度小于 10 个字符。

我用于构建的代码是

nasm -f elf64 strlen.asm && ld strlen.o -o strlen && ./strlen

我有两个问题:

  1. 此代码编译为 64 位,而代码本身为 32 位。我应该应用哪些更改才能使此代码也成为 64 位?
  2. 为什么应用程序总是报告长度多出一个字节?从理论上讲,它不计算空终止。给定的文本是否包含\x10or \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


标签: assembly64-bitx86-64nasm

解决方案


推荐阅读