The following exercise is from an Assembler-course I'm taking:
Write a program that takes a number x as input, and returns:
- 0 if x is even.
- 1 if x is odd.
Full exercise-page here: GitHub
Here's my solution:
format PE console
entry start
include 'win32a.inc'
; ===============================================
section '.text' code readable executable
start:
call read_hex ; Provided by the teacher. Reads a hexadecimal number from stdin.
and eax, 0x1
cmp eax, 0x0
je print_result
mov eax, 0x1
print_result:
call print_eax_binary ; Provided by the teacher. Prints a binary number to stdout.
; Exit the process:
push 0
call [ExitProcess]
include 'training.inc'
I would say it works alright:
- Is my solution valid?
- Can it be improved? Respectively, is there a better solution possible?
1 Answer 1
Here are some things that may help you improve your code.
Simplify your code
This can certainly be simplified. Keep the goal in mind: get either 0 or 1 into EAX
. Once you've executed this instruction:
and eax, 0x1
That's exactly what you have. So that means all of this can be deleted:
cmp eax, 0x0
je print_result
mov eax, 0x1
print_result:
And all you need to do is print the result:
call print_eax_binary