Assembly, writing a single byte from register to memory overwrites other bytes

Viewed 2333

In 64bit x86 assembly nasm, how can I move a single byte from the register into a memory location defined in section .data?

I understand that this works

global _main

section .data
quotient db 0x0, 0x0, 0x30, 0xa ; 3 digit + newline
remainder db 0x0, 0x0, 0x30, 0xa; 3 digit + newline

section .text

_main:
mov rax, 0x2000004
mov rdi, 1
mov rsi, quotient
mov rdx, 8
syscall ; outputs 0 /newline 0 /newline as expected

exit:
mov rax, 0x2000001
mov rdi, 0
syscall

Also I know you can set a single byte using a byte keyword

mov rbx, quotient ; move location of quotient into memory
mov [rbx], byte 0x31 ; change first byte to ascii '1'

this would output 1 0 /newline 0 /newline as expected

However suppose I want to set it as a register value

mov rbx, quotient ; move location of quotient into memory
mov r8, 0x31 ; set another register to ascii '1'
mov [rbx], r8 ; write the register value into memory

This does output 1 but it seems to overwrite every byte in memory after that so the newlines get removed.

My question is how can I write a single 'byte' from register into the memory location?

1 Answers

64 bit registers contain 8 bytes so writing a register into memory via

mov [rbx], r8

will move 8 bytes into the memory location starting at rbx

The table below shows how to write 1,2,4 bytes out of any register into memory

enter image description here

So for example writing one byte (byte 0) out of the r8 register would be

mov [rbx], r8b

one byte out of rax would be

mov [rbx], al

reference: http://cs.brown.edu/courses/cs033/docs/guides/x64_cheatsheet.pdf

Related