Sabien
Sabien

Reputation: 219

store a number into a variable in assembly language

I'm trying to write a simple program in assembly to add and subtract numbers. I'm using NASM to assemble the program. When I evaluate the program with gdb, the registers do not have the values I expect and I can't figure out why. Here's my code. Right now, I'm just trying to figure out how to store a number into a variable, and then move that variable into a register, because my code is not even doing that.

SECTION .data
    var1: db 0x1      ; assign 1 to var1
    var2: db 0x2      ; assign 4 to var2
    var3: db 0x4      ; assign 6 to var3
    var4: db 0x8      ; assign 8 to var4

SECTION .bss
                   ; empty for now

SECTION .text
global _start

_start:

    nop                        ; keep gdb happy
    mov eax, [var1]            ; keep gdb happy


... more code ...

    mov eax, 1                 ; clean up
    mov ebx, 0
    int 80H

Now when I open my program in gdb and look at eax after the first assignment, the value is 0x10806 and not just 0x1. Why is this happening?

Upvotes: 1

Views: 10281

Answers (2)

Guffa
Guffa

Reputation: 700690

The eax register is a 32 bit register, and the variables are eigth bit values. When you try to read one variable into the register, you get all four.

You can use 32 bit variables with the dd declaration instead of db:

var1: dd 0x1      ; assign 1 to var1
var2: dd 0x2      ; assign 2 to var2
var3: dd 0x4      ; assign 4 to var3
var4: dd 0x8      ; assign 8 to var4

Upvotes: 3

m0skit0
m0skit0

Reputation: 25874

Because EAX is 32 bits and you're moving one byte, so only AL is changed, the rest of the register will retain is previous value. I suggest you zero the EAX register first (with for example xor eax, eax)

Upvotes: 0

Related Questions