117k views
2 votes
Using assembly

Read 1 byte. Write a program that prints:

It's a B

if the input is a B

It's NOT a A

if the input is not the letter B

helpful code
;nasm 2.13.02

section .data
message: db 'Same',10
messageLen: equ $-message

messageNOT: db 'NOT same',10
messageNOTLen: equ $-messageNOT

section .text
global _start

_start:

; compare if I have a 5
mov al,'X'
cmp al,'C'
je same

mov eax,4
mov ebx,1
mov ecx,messageNOT
mov edx,messageNOTLen
int 80h
jmp end
same:
mov eax,4
mov ebx,1
mov ecx,message
mov edx,messageLen
int 80h
end:
mov eax,1
mov ebx,0
int 80h;

User SuitUp
by
8.3k points

1 Answer

6 votes

Answer:

Here's an example program written in NASM x86 assembly that reads one byte of input and prints a message depending on whether the input is a B or not:

section .data

message_b: db "It's a B",10

message_not_b: db "It's NOT a B",10

section .bss

input_buffer: resb 1

section .text

global _start

_start:

; read one byte of input from stdin

mov eax, 3

mov ebx, 0

mov ecx, input_buffer

mov edx, 1

int 0x80

; check if input is B

cmp byte [input_buffer], 'B'

jne not_b

; print "It's a B" message

mov eax, 4

mov ebx, 1

mov ecx, message_b

mov edx, 8

int 0x80

jmp end

not_b:

; print "It's NOT a B" message

mov eax, 4

mov ebx, 1

mov ecx, message_not_b

mov edx, 12

int 0x80

end:

; exit program

mov eax, 1

xor ebx, ebx

int 0x80

Step-by-step explanation:

The program first declares two messages, one for when the input is a B and another for when it's not. It then reserves one byte of memory for the input buffer using the .bss section.

In the .text section, the program first reads one byte of input from stdin using the read system call. It then compares the input to the ASCII value of the letter B using the cmp instruction. If the input is not B, it jumps to the not_b label to print the "It's NOT a B" message. If the input is B, it continues to print the "It's a B" message.

The program uses the mov instruction to load the appropriate values into the registers required by the write system call. The message to be printed is stored in the ecx register, while the length of the message is stored in the edx register. The int 0x80 instruction is then used to invoke the write system call and print the message to stdout.

Finally, the program exits using the exit system call by loading the value 1 into the eax register and calling int 0x80.

User Ruttydm
by
7.2k points