You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

x86架构NASM代码复制字节时遇无效有效地址错误求助

Fixing "Invalid effective address" in NASM for x86 Hex Digit Copy

Got it, let's break down why you're running into that "Invalid effective address" error and get your hex digit copy working correctly.

The Root of the Problem

x86 assembly has strict rules for effective memory addresses—you can't just use ax directly as an index into an array like you would in C. Here are the two key issues with your original approach:

  1. x86 doesn't allow ax as a base or index register for memory addressing. Only registers like bx, si, di, bp (and their 32-bit counterparts if you're in 32-bit mode) are valid for this.
  2. You can't do a direct memory-to-memory mov instruction—you need to use a general-purpose register as a middleman to hold the byte you're copying.

The Solution

Let's rewrite the code step by step to fix both issues:

First, here's your data section for reference:

section .data
    hex_digits: db '0123456789abcdef'  ; 16 hex characters, indexes 0-15
    hex_out: db '0000'                 ; 4-byte string, indexes 0-3

Now, in your text section, here's how to safely copy hex_digits[ax] to hex_out[3]:

section .text
    global _start

_start:
    ; Let's say ax already holds your target index (e.g., 0x05 for '5')
    mov ax, 0x05

    ; Step 1: Move ax's value to a valid index register (bx here)
    mov bx, ax
    ; Step 2: Load the byte from hex_digits[bx] into al (8-bit register, since we're dealing with a single byte)
    mov al, [hex_digits + bx]
    ; Step 3: Store the byte from al into hex_out[3] (hex_out + 3 is the memory address of the 4th character)
    mov [hex_out + 3], al

    ; Optional: Add code to print hex_out or exit cleanly here
    ; ...

Key Notes

  • Valid Index Registers: If you prefer, you could use si or di instead of bx—all three are valid for base/index addressing in x86.
  • Range Check: Since hex_digits only has 16 elements (indexes 0-15), make sure ax is between 0 and 15 before doing the copy. If ax is larger, you'll access memory outside your array, which can cause crashes or unexpected behavior.
  • Memory-to-Memory Restriction: Remember, x86 mov can't transfer directly from one memory location to another—always use a register as an intermediary.

内容的提问来源于stack exchange,提问作者Jacob Garby

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:30:37