117k views
3 votes
Write an assembly program to read a number between 0 and 9, then print it

1 Answer

7 votes

Answer:

Step-by-step explanation:

Here's an example assembly program written in x86 NASM syntax for Linux that reads a single digit from user input and prints it to the console:

section .data

prompt db "Enter a single digit (0-9): ", 0

output db "You entered: ", 0

section .bss

input resb 2 ; reserve 2 bytes of memory for user input

section .text

global _start

_start:

; prompt user for input

mov eax, 4 ; system call for 'write'

mov ebx, 1 ; file descriptor 1 (stdout)

mov ecx, prompt ; pointer to prompt string

mov edx, 27 ; length of prompt string

int 0x80 ; call kernel to write to console

; read user input

mov eax, 3 ; system call for 'read'

mov ebx, 0 ; file descriptor 0 (stdin)

mov ecx, input ; pointer to input buffer

mov edx, 2 ; read up to 2 bytes (1 digit + newline)

int 0x80 ; call kernel to read from console

; convert input to integer

movzx eax, byte [input] ; move ASCII digit to eax register

sub eax, '0' ; subtract ASCII code for '0' to convert to integer

; print output

mov ebx, 1 ; file descriptor 1 (stdout)

mov ecx, output ; pointer to output string

mov edx, 14 ; length of output string

int 0x80 ; call kernel to write to console

add al, '0' ; convert integer back to ASCII code

mov [output + 14], al ; store digit in output buffer after the output string

mov eax, 4 ; system call for 'write'

mov ebx, 1 ; file descriptor 1 (stdout)

mov ecx, output ; pointer to output buffer

mov edx, 15 ; length of output string + digit

int 0x80 ; call kernel to write to console

; exit program

mov eax, 1 ; system call for 'exit'

xor ebx, ebx ; exit status code 0

int 0x80 ; call kernel to exit

The program first prompts the user to enter a single digit between 0 and 9. It then reads the user input and converts it from ASCII code to an integer. Finally, it prints the user's input as a digit to the console.

Note that this program assumes the user enters a single digit followed by a newline character. If the user enters more than one digit or any non-digit characters, the program behavior is undefined. Also, this program uses the x86 32-bit architecture and Linux system calls.

User Toine Db
by
7.2k points