user2798943
user2798943

Reputation: 197

How to load a single byte from address in assembly

How can I load a single byte from address? I thought it would be something like this:

mov      rax, byte[rdi]

Upvotes: 3

Views: 8242

Answers (1)

ikh
ikh

Reputation: 10417

mov al, [rdi]

Merge a byte into the low byte of RAX.


Or better, avoid a false dependency on the old value of RAX by zero-extending into a 32-bit register (and thus implicitly to 64 bits) with MOVZX:

movzx  eax, byte [rdi]       ; most efficient way to load one byte on modern x86

Or if you want sign-extension into a wider register, use MOVSX.

movsx  eax, byte [rdi]    ; sign extend to 32-bit, zero-extend to 64
movsx  rax, byte [rdi]    ; sign extend to 64-bit

(On some CPUs, MOVSX is just as efficient as MOVZX, handled right in a load port without even needing an ALU uop. https://uops.info. But there are some where MOVZX loads are cheaper than MOVSX, so prefer MOVZX if you don't care about the upper bytes and really just want to avoid partial-register shenanigans.)


The MASM equivalent replaces byte with byte ptr.

A mov load doesn't need a size specifier (al destination implies byte operand-size). movzx always does for a memory source because a 32-bit destination doesn't disambiguate between 8 vs. 16-bit memory sources.

The AT&T equivalent is movzbl (%rdi), %eax (with movzb specifying that we zero-extend a byte, the l specifying 32-bit destination size.)

Upvotes: 10

Related Questions