In: Computer Science
Question1. (lesson 2)
In the following code we determine a number if its even or odd. Explain what logic is used for that?
section .text
global _start ;must be declared for using gcc
_start: ;tell linker entry point
mov ax, 8h ;getting 8 in the ax
and ax, 1 ;and ax with 1
jz evnn
mov eax, 4 ;system call number (sys_write)
mov ebx, 1 ;file descriptor (stdout)
mov ecx, odd_msg ;message to write
mov edx, len2 ;length of message
int 0x80 ;call kernel
jmp outprog
evnn:
mov ah, 09h
mov eax, 4 ;system call number (sys_write)
mov ebx, 1 ;file descriptor (stdout)
mov ecx, even_msg ;message to write
mov edx, len1 ;length of message
int 0x80 ;call kernel
outprog:
mov eax,1 ;system call number (sys_exit)
int 0x80 ;call kernel
section .data
even_msg db 'Even Number!' ;message showing even number
len1 equ $ - even_msg
odd_msg db 'Odd Number!' ;message showing odd number
len2 equ $ - odd_msg
Question 2. (lesson 1 and lesson 3)
Write a program that does the following(modification from assignment 3)
1. Asks the user to enter two numbers (each is a byte) A and B
2. Multiply the numbers and stores the result in variable C.
3. so that if the product exceeds 10, the program would print “result is greater than 10”.
Otherwise (if result < 10), it prints the result as usual.
First question
To find whether a number a number is even or odd, we check its least significant bit in binary representaion. If the Least Significant Bit is 1, the number is odd, otherwise it is even. Here, AND operation is performed between the variable ax and 1. In the line jz evnn, it is being checked whether after performing the AND operation, the value in z is zero(0) or not. If the value of z is zero, the number is even. Otherwise it is odd.
In AND operation, the answer is one only when both the input bits are one, otherwise the answer is zero. So, the last bit of the number when combined with one through AND operation, gives one when it is one(indicating number is odd), or gives zero, when it is zero(indicating number is even).
Second Question
global_start
A DB ?
B DB ?
MSG1 DB 10,13,”ENTER FIRST NUMBER : $”
MSG2 DB 10,13,”ENTER SECOND NUMBER : $”
MSG3 DB 10,13,”Result is greater than 10 : $”
ENDS
CODE SEGMENT ASSUME DS:DATA CS:CODE START: MOV AX,DATA MOV DS,AX LEA DX,MSG1 MOV AH,9 INT 21H MOV AH,1 INT 21H SUB AL,30H MOV A,AL LEA DX,MSG2 MOV AH,9 INT 21H MOV AH,1 INT 21H SUB AL,30H MOV B,AL MUL A MOV C,AL AAM ADD AH,30H ADD AL,30H MOV BX,AX CMP BX, #10 GT BX,#10 LEA DX,MSG3 MOV AH,9 INT 21H MOV AH,2 MOV DL,BH INT 21H MOV AH,2 MOV DL,BL INT 21H MOV AH,4CH INT 21H ENDS END START