汇编语言寄存器赋值疑问:mov reg,5时高低段存储位置及原因
mov reg, 5指令中数值5的存储位置问题解答 Great question! Let's break this down, focusing on the widely used x86/x86_64 architectures (since those are the ones with split high/low register segments):
16-bit registers (e.g., AX, BX, CX)
When you runmov AX, 5, the value 5 (binary00000101) gets stored in the low 8-bit segment of the register (that'sALfor AX,BLfor BX). The high 8-bit segment (AH/BH) will be zeroed out automatically via zero-extension. This makes sense because 5 is an 8-bit value, and the assembler optimizes to use the smallest possible valid segment—plus, you can later directly accessALto get the value 5 without dealing with the rest of the register.32-bit registers (e.g., EAX, EBX, ECX)
Here, 5 gets zero-extended to a 32-bit value:0x00000005. The actual meaningful data is in the lowest 8 bits of the 32-bit register, with the upper 24 bits filled with zeros. Even though the entire register holds the full 32-bit value, the "active" part of the small number lives in the low byte segment.64-bit registers (e.g., RAX, RBX, RCX)
Same logic applies: 5 becomes the 64-bit value0x0000000000000005, with the value 5 residing in the lowest 8 bits (the equivalent ofALfor RAX), and all higher bits set to zero.
Why this happens?
- Immediate size optimization: Assemblers prioritize using the smallest possible immediate value size that fits the data. Since 5 fits in 8 bits, it's treated as an 8-bit value first, then extended to match the register's full width.
- Hardware register design: x86 registers are designed so their low segments (like AL, BL) are directly accessible as standalone 8-bit registers. Storing small values here lets you easily manipulate just that byte later without extra operations.
- Extension rules: For positive integers like 5, zero-extension fills all higher bits with zeros—this is the default behavior for unsigned immediate values in x86 assembly.
Note: This behavior is specific to architectures with split register segments (like x86). RISC architectures (e.g., ARM) typically don't split registers into high/low parts, so the full register would hold the zero-extended value of 5 instead.
内容的提问来源于stack exchange,提问作者Muhammad Faizan

