Hi, I am having trouble when I read in an integer from the keyboard and I try to display it to the screen back as the same integer. It pops out as an ASCII character. Am I doing this wrong or is there a way to read it as an integer and not a character, or do I need to convert it back? Thanks

; Compiling this code for 32-bit use:
;    nasm -f elf file.asm
;    gcc -m32 -o file file.o
;
;~.~. Definitions for readability: ~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.~.
        %define  SYS_EXIT   1
        %define  SYS_READ   3
        %define  SYS_WRITE  4

        %define  STDIN      0
        %define  STDOUT     1
        %define  STDERR     2

        %define  MAX_NUMBER   5000


SECTION .data
format: db "The number is %d." , 10

SECTION .bss
input: resd MAX_NUMBER

SECTION .text
extern printf
global main

main:
nop
GetInput:
        mov EAX, SYS_READ
        mov EBX, STDIN
        mov ECX, input
        int 80H
        mov DWORD[input + EAX - 1], 0

Calculate:
        mov EAX, DWORD[input]
Display:
        push EAX
        push format
        call printf
        add ESP, 8
        ret                 

Everything you get from the keyboard is a character. To extract an integer you need to read multiple characters and append them to an integer value, or store them as a string and then subsequently convert that string to an integer value. Either way you're doing a string to integer conversion.

Since you're using printf, why not also use scanf? That way scanf will do all of the hard work in converting:

extern  scanf
extern  printf

global  main

section .data

; Don't forget terminating null characters to match C's expectation
ifmt: db "%d", 10, 0
ofmt: db "The number is %d.", 10, 0

section .bss

input:  resd    1       ; resd reserves N dwords, not 1 dword if N length

section.text

main:
    push    dword[input]    ; Variables can be added directly in NASM
    push    ifmt
    call    scanf
    add esp, 8

    push    dword[input]
    push    ofmt
    call    printf
    add esp, 8

    mov eax, 0      ; Return 0 for consistency with C programs
    ret

Thanks to all who helped I have solved this using scanf() C call.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.